Mr.*_*Zen 9 r rcpp rcpparmadillo
我通常使用一个简短的 Rcpp 函数,该函数将一个矩阵作为输入,其中每行包含 K 个总和为 1 的概率。然后该函数为每一行随机采样 1 到 K 之间的整数,对应于提供的概率。这是函数:
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadilloExtensions/sample.h>
using namespace Rcpp;
// [[Rcpp::export]]
IntegerVector sample_matrix(NumericMatrix x, IntegerVector choice_set) {
int n = x.nrow();
IntegerVector result(n);
for ( int i = 0; i < n; ++i ) {
result[i] = RcppArmadillo::sample(choice_set, 1, false, x(i, _))[0];
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
我最近更新了 R 和所有软件包。现在我不能再编译这个函数了。我不清楚原因。跑步
library(Rcpp)
library(RcppArmadillo)
Rcpp::sourceCpp("sample_matrix.cpp")
Run Code Online (Sandbox Code Playgroud)
引发以下错误:
error: call of overloaded 'sample(Rcpp::IntegerVector&, int, bool, Rcpp::Matrix<14>::Row)' is ambiguous
Run Code Online (Sandbox Code Playgroud)
这基本上告诉我,我的电话RcppArmadillo::sample()是模棱两可的。任何人都可以启发我为什么会这样吗?
这里发生了两件事,你的问题有两个部分,因此答案。
第一个是“元”:为什么是现在?好吧,我们在sample()代码/设置中有一个错误,Christian 为最新的 RcppArmadillo 版本友好地修复了这个错误(并且都记录在那里)。简而言之,这里给您带来麻烦的非常概率论点的界面已更改,因为它对于重用/重复使用不安全。就是现在。
第二,错误信息。你没有说你使用什么编译器或版本,但我的(目前g++-9.3)实际上对错误很有帮助。它仍然是 C++,所以需要一些解释性的舞蹈,但本质上它清楚地说明你调用了 withRcpp::Matrix<14>::Row并且没有为该类型提供接口。哪个是正确的。sample()提供了一些接口,但没有一个Row对象。因此,修复再次简单。添加一行以通过使行 a 来帮助编译器NumericVector,一切都很好。
#include <RcppArmadillo.h>
#include <RcppArmadilloExtensions/sample.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
// [[Rcpp::export]]
IntegerVector sample_matrix(NumericMatrix x, IntegerVector choice_set) {
int n = x.nrow();
IntegerVector result(n);
for ( int i = 0; i < n; ++i ) {
Rcpp::NumericVector z(x(i, _));
result[i] = RcppArmadillo::sample(choice_set, 1, false, z)[0];
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
R> Rcpp::sourceCpp("answer.cpp") # no need for library(Rcpp)
R>
Run Code Online (Sandbox Code Playgroud)