2017-12-31 56 views
-3

5x5 행렬을 갖고 있으며 열 "1"과 "3"사이에서 가장 작은 값의 인덱스를 찾고 싶습니다. R에서 나는 다음과 같이 할 것 :Rcpp가있는 행렬의 두 특정 열 사이의 최소값 인덱스를 찾는 방법은 무엇입니까?

set.seed(1984) 
m <- matrix(sample.int(25,25), 5) 
min <- which(m[,c(1,3)] == min(m[,c(1,3)]), arr.ind = TRUE) 

Rcpp에 있음을 수행하는 가장 효율적인 방법은 무엇입니까?

+6

http://idownvotedbecau.se/noattempt/ – Murphy

+2

그를 downvoting 이유는 무엇입니까? 어쩌면 그냥 설명하고 그를 도울 수 있습니다 ... 당신은 R 공동체를 운영하고 있습니다 –

답변

4

나는 그것이 더 강력한 매트릭스 조작이로 이상 RcppRcppArmadillo를 사용하도록 선택할 것입니다. 예를 들어, 서브 세트의 index_min() or index_max()을 신속하게 찾은 다음 ind2sub()을 사용하여 첨자 표기법으로 변환 할 수 있습니다. 주목을 한가지 C++이 목표는 R에 인덱스 첨자를 사용하는 경우 을 추가해야한다, 그래서 1 기반의 인덱스를 사용하여 0 기반 인덱스 및 R을 사용합니다.

귀하의 경우에 다음과 같은 작업을해야합니다 :

#include <RcppArmadillo.h> 
// [[Rcpp::depends(RcppArmadillo)]] 

// [[Rcpp::export]] 
arma::urowvec get_min_cols(const arma::mat& x, const arma::uvec& col_indexes) { 

    // Obtain the minimum index from the selected columns 
    arma::uword min_index = x.cols(col_indexes).index_min(); 

    // Obtain the subscript notation from index based on reduced dimensions 
    arma::uvec min_subnot = arma::ind2sub(arma::size(x.n_rows, col_indexes.n_elem), 
             min_index); 

    // Transpose to row vector and 
    // translate indices to _R_ from _C++_ by adding 1 
    return min_subnot.t() + 1; 
} 

테스트 :

set.seed(1984) 
m = matrix(sample.int(25,25), 5) 

col_indexes = c(1, 3) 

min_loc_r = which(m[, col_indexes] == min(m[, col_indexes]), arr.ind = TRUE) 

# Note that the column indices has been translated to C++ 
min_loc_cpp = get_min_cols(m, col_indexes - 1) 

min_loc_r 
#  row col 
# [1,] 5 2 

min_loc_cpp 
#  [,1] [,2] 
# [1,] 5 2 
+2

대단히 감사합니다! 그런데 thecoatlessprofessor.com/programming/rcpp/...에서 아주 멋진 문서 !! 내가 질문을 게시하기 직전에 비공식 Rcpp API 문서를 연구하고있었습니다. 그것은 고품질의 소재입니다. 나는 sapply() 나 which_min() 같은 Rcpp 설탕 함수로 뭔가를 할 수 있다고 생각했지만, 힘든 시간을 보냈습니다 !! 다시 한 번 감사드립니다! 도와 주셔서 정말 고맙습니다 !! – allanvc

관련 문제