作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我想在要与 Rcpp 一起使用的 C++ 代码中使用 R 函数 rmultinom。我得到一个关于参数不足的错误 - 我不熟悉这些参数应该是什么,因为它们与 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 业务。谢谢!
顺便说一句,对于与 this thread 的相似之处,我深表歉意。 , 但是
最佳答案
以下是 user95215 的答案,修改后可以编译,另一个版本更符合 Rcpp 风格:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
IntegerVector oneMultinomC(NumericVector probs) {
int k = probs.size();
SEXP ans;
PROTECT(ans = Rf_allocVector(INTSXP, k));
probs = Rf_coerceVector(probs, REALSXP);
rmultinom(1, REAL(probs), k, &INTEGER(ans)[0]);
UNPROTECT(1);
return(ans);
}
// [[Rcpp::export]]
IntegerVector oneMultinomCalt(NumericVector probs) {
int k = probs.size();
IntegerVector ans(k);
rmultinom(1, probs.begin(), k, ans.begin());
return(ans);
}
关于c++ - 将 rmultinom 与 Rcpp 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24618370/
我想从具有三个值(例如 1,2 和 3)的多项分布生成大小为 20 的样本。例如,示例可以是这样的 sam=(1,2,2,2,2,3,1,1,1,3,3,3,2,1,2,3,... 1) 下面的代码可
我想在要与 Rcpp 一起使用的 C++ 代码中使用 R 函数 rmultinom。我得到一个关于参数不足的错误 - 我不熟悉这些参数应该是什么,因为它们与 R 中函数使用的参数不对应。我也没有运气使
我是一名优秀的程序员,十分优秀!