我编写了一个函数qSelectMbycol
,它在 O(n) 时间内Rcpp
返回k
每列的第 th 个最大元素。此功能工作正常。如果我尝试做同样的事情但处理行而不是列(函数qSelectMbyrow
),它会返回错误"error: Mat::init(): requested size is not compatible with column vector layout"
。有人想我做错了什么吗?我将此文件保存为“ qselect.cpp
”:
// [[Rcpp::depends(RcppArmadillo)]]
#define RCPP_ARMADILLO_RETURN_COLVEC_AS_VECTOR
#include <RcppArmadillo.h>
using namespace arma;
// [[Rcpp::export]]
arma::vec qSelectMbycol(arma::mat& M, const int k) {
// ARGUMENTS
// M: matrix for which we want to find the k-th largest elements of each column
// k: k-th statistic to look up
arma::mat Y(M.memptr(), M.n_rows, M.n_cols);
// we apply over columns
int c = M.n_cols;
arma::vec out(c);
int i;
for (i = 0; i < c; i++) {
arma::vec y = Y.col(i);
std::nth_element(y.begin(), y.begin() + k - 1, y.end());
out(i) = y(k-1); // the k-th largest value of each column
}
return out;
}
// [[Rcpp::export]]
arma::vec qSelectMbyrow(arma::mat& M, const int k) {
// ARGUMENTS
// M: matrix for which we want to find the k-th largest elements of each row
// k: k-th statistic to look up
arma::mat Y(M.memptr(), M.n_rows, M.n_cols);
// we apply over rows
int r = M.n_rows;
arma::vec out(r);
int i;
for (i = 0; i < r; i++) {
arma::vec y = Y.row(i); // this line throws the error "error: Mat::init(): requested size is not compatible with column vector layout"
std::nth_element(y.begin(), y.begin() + k - 1, y.end());
out(i) = y(k-1); // should give k-th largest value of each row
}
return out;
}
例子:
n=500
p=100
set.seed(1)
M=matrix(rnorm(n, mean = 100, sd = 1),n,1)
library(Rcpp)
library(RcppArmadillo)
Rcpp::sourceCpp('qselect.cpp')
qSelectMbycol(M,5) # works OK
qSelectMbyrow(M,5) # throws error "error: Mat::init(): requested size is not compatible with column vector layout"
我也尝试插入
typedef std::vector<double> stdvec;
并将线设置向量替换y
为
arma::vec y = arma::conv_to<stdvec>::from(Y.row(i));
在我的qSelectMbyrow
函数中,虽然该函数随后运行,但与应用列相比它运行缓慢,并且如果我运行它 100 次也会使我的 R 会话崩溃。