c++ - Armadillo vector 类的 RcppArmadillo 样本

标签 c++ r rcpp armadillo

我们一直在使用 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 函数的多个定义有关。具体地输入定义所需函数的 namespace 可以解决问题。特别是,需要从 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;
}

关于c++ - Armadillo vector 类的 RcppArmadillo 样本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43353109/

相关文章:

c++ - 如何在 Visual Studio 2013 中动态包含库

r - R 中具有不等行的绑定(bind)矩阵

r - 基于唯一列交互的虚拟变量

c++ - C++11中列表初始化的优点

c++ - 如何判断以 CreateProcess 启动的进程是否仍在运行?

r - 使用facet_wrap仅在某些子图中释放y轴

r - 在 Rcpp 中生成多元高斯分布

c++ - 通过 C 中的指针从 R 中的 big.matrix 访问一 block 内存

R 重新编译包失败,因为失败

C++ new 分配比预期更多的空间