【问题标题】:RcppArmadillo sample on armadillo vector classes犰狳矢量类上的 RcppArmadillo 样本
【发布时间】:2017-04-11 17:58:45
【问题描述】:

我们一直在使用RcppArmadillo 中的sample 函数来随机采样NumericVector 对象。然而,我们注意到不可能在犰狳类型(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]

对此的任何帮助将不胜感激:)

【问题讨论】:

  • 你能快速确认RcppArmadillo的版本是最新的吗? sessionInfo() >=7.6
  • sessionInfo() 的输出:RcppArmadillo_0.7.700.0.0
  • 作为第一步(防御),撤消 using namespace ...,因为我们现在有 两个 sample 函数。
  • 尝试注释掉两个using namespace 行并得到更多错误。还尝试了每个注释中的一个,但仍然出现错误。但是,特别是在所有内容之前输入每个命名空间,我能够让它工作,但是 sample 函数需要被称为 Rcpp::RcppArmadillo::sample(sequence, size, false)

标签: c++ r rcpp armadillo


【解决方案1】:

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

以下代码可以按需要工作。

// [[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;
}

【讨论】:

  • 请删除文件顶部的namespace 声明。你没有使用它们。这可能会咬到其他复制和粘贴代码的人。
  • 我会将其改写为:“鉴于现在在 RcppRcppArmadillo 命名空间中都有两个 sample() 实现(后者仍然是可选的),您需要更加明确关于您选择的内容。”
  • 链接到相关问题:stackoverflow.com/q/44060134/1169233
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多