如何使用 Rcpp 找到矩阵的两个特定列之间的最小值的索引?
How to find the index of the minimum value between two specific columns of a matrix with Rcpp?
我有一个 5x5 矩阵,想找到列“1”和“3”之间最小值的索引。在 R 我会这样做:
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 最有效的方法是什么?
我会选择使用 RcppArmadillo 而不是 Rcpp,因为它具有更强大的矩阵操作。例如,您可以找到 index_min()
or index_max()
of a subset quickly and then translate it to subscript notation with ind2sub()
。需要注意的一件事是 C++ 使用基于 0 的索引,而 R 使用基于 1 的索引,因此您应该确保添加 1如果目标是使用索引下标在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
我有一个 5x5 矩阵,想找到列“1”和“3”之间最小值的索引。在 R 我会这样做:
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 最有效的方法是什么?
我会选择使用 RcppArmadillo 而不是 Rcpp,因为它具有更强大的矩阵操作。例如,您可以找到 index_min()
or index_max()
of a subset quickly and then translate it to subscript notation with ind2sub()
。需要注意的一件事是 C++ 使用基于 0 的索引,而 R 使用基于 1 的索引,因此您应该确保添加 1如果目标是使用索引下标在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