gpt4 book ai didi

c++ - 将 rmultinom 与 Rcpp 结合使用

转载 作者:太空狗 更新时间:2023-10-29 20:59:27 24 4
gpt4 key购买 nike

我想在要与 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 的相似之处,我深表歉意。 , 但是

  1. 答案不符合我的目的
  2. 差异可能足以引发不同的问题(您认为是这样吗?)
  3. 该问题是一年前发布和回答的。

最佳答案

以下是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com