2017-12-31 217 views
-3

私は5x5の行列を持ち、列 "1"と "3"の間の最小値のインデックスを探したいと思っています。 Rでは、私は次のように行います:行列の2つの特定の列の間の最小値のインデックスを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++で0ベースのインデックスを使用して、あなたは目標がRでインデックスの添字を使用する場合を追加することを確認しなければならないので、Rは1ベースのインデックスを使用しています。

次はあなたのケースのために働く必要があります。

#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

関連する問題