我想在 C++ 代码中使用 R 函数rmultinom与 Rcpp 一起使用。我收到一个关于没有足够参数的错误 - 我不熟悉这些参数应该是什么,因为它们与 R 中的函数使用的参数不对应。我也没有任何运气使用“::Rf_foo”从 Rcpp 代码访问 R 函数的语法。
下面是我的代码的简化版本(是的,我正在编写一个 gibbs 采样器)。
#include <Rcpp.h>
using namespace Rcpp;
// C++ implementation of the R which() function.
int whichC(NumericVector x, double val) {
int ind = -1;
int n = x.size();
for (int i = 0; i < n; ++i) {
if (x[i] == val) {
if (ind == -1) {
ind = i;
} else {
throw std::invalid_argument( "value appears multiple times." );
}
} // end if
} // end for
if (ind != -1) {
return ind;
} else {
throw std::invalid_argument( "value doesn't appear here!" );
return -1;
}
}
// [[Rcpp::export]]
int multSample(double p1, double p2, double p3) {
NumericVector params(3);
params(0) = p1;
params(1) = p2;
params(2) = p3;
// HERE'S THE PROBLEM.
RObject sampled = rmultinom(1, 1, params);
int out = whichC(as<NumericVector>(sampled), 1);
return out;
}
我是 C++ 的新手,所以我意识到很多这段代码可能很笨拙且效率低下。我愿意接受有关如何改进我的 c++ 代码的建议,但我的首要任务是了解 rmultinom 业务。谢谢!
顺便说一句,我为与此线程的相似之处道歉,但是
- 答案对我的目的不起作用
- 差异可能足以证明一个不同的问题(你认为是吗?)
- 这个问题是在一年前发布并回答的。