问题
I have a 5x5 matrix and want to find the index of the smallest value between columns "1" and "3". In R I would do like this:
set.seed(1984)
m <- matrix(sample.int(25,25), 5)
min <- which(m[,c(1,3)] == min(m[,c(1,3)]), arr.ind = TRUE)
What is the most efficient way of doing that with Rcpp?
回答1:
I would opt to use RcppArmadillo over Rcpp as it has more robust matrix manipulation. For instance, you can find the index_min() or index_max() of a subset quickly and then translate it to subscript notation with ind2sub(). One thing to take note of is C++ uses 0-based indices and R uses 1-based indices so you should make sure to add 1 if the goal is to use the index subscript in R.
The following should work for your case:
#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;
}
Test:
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
来源:https://stackoverflow.com/questions/48045895/how-to-find-the-index-of-the-minimum-value-between-two-specific-columns-of-a-mat