犰狳向量上的 RcppArmadillo 样本 类

RcppArmadillo sample on armadillo vector classes

我们一直在使用 RcppArmadillo 中的 sample 函数随机抽取一个 NumericVector 对象。但是,我们注意到无法在 Armadillo 类型(vecuvec)上使用相同的函数。我们已经查看了 sample.h 文件中的函数定义,它看起来像是一个应该能够与这些类型一起工作的模板化函数,但我们还无法弄清楚如何让它与 Armadillo 类 而无需对 Rcpp 库中的 NumericVectorIntegerVector 类型进行大量转换。

例如,我们将这个函数写在一个名为try.cpp.

的文件中
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
#include <RcppArmadilloExtensions/sample.h>

using namespace arma;
using namespace Rcpp;

// [[Rcpp::export]]
arma::uvec sample_index(const int &size){
    arma::uvec sequence = linspace<uvec>(0, size-1, size);
    arma::uvec out = sample(sequence, size, false);
    return out;
}

运行 上面的代码会产生以下错误:

src/try.cpp|11 col 22 error| no matching function for call to 'sample' [cpp/gcc]      

~/Library/R/3.3/library/Rcpp/include/Rcpp/sugar/functions/sample.h|401 col 1 error| note: candidate function not viable: no known conversion from 'arma::uvec' (aka 'Col<unsigned int>') to 'int' for 1st argument [cpp/gcc]

~/Library/R/3.3/library/Rcpp/include/Rcpp/sugar/functions/sample.h|437 col 1 error| note: candidate template ignored: could not match 'Vector' against 'Col' [cpp/gcc]

如有任何帮助,我们将不胜感激:)

万一以后有人遇到这个问题,这个问题似乎与正在使用的命名空间中 sample 函数的多个定义有关。专门键入定义所需函数的名称空间可以解决问题。特别是,需要从 Rcpp::RcppArmadillo.

调用 sample 函数

以下代码可以正常工作。

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

// [[Rcpp::export]]
arma::uvec sample_index(const int &size){
    arma::uvec sequence = arma::linspace<arma::uvec>(0, size-1, size);
    arma::uvec out = Rcpp::RcppArmadillo::sample(sequence, size, false);
    return out;
}