犰狳媒介类的RCPP犰狳样本

RcppArmadillo sample on armadillo vector classes

本文关键字:RCPP 样本      更新时间:2023-10-16

我们一直在使用 sample 函数从 RcppArmadillo 随机采样NumericVector对象。但是,我们注意到不可能在犰狳类型(vecuvec(上使用相同的功能。我们已经查看了sample.h文件中的函数定义,它看起来像一个应该能够使用这些类型的模板化函数,但是我们无法弄清楚如何使其与犰狳类一起工作,而无需从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;
}