Rcpp 中 AR(1) 的模拟

Simulation of AR(1) in Rcpp

有没有一种方法可以使用 Rcpp 糖调用 arima.sim?到目前为止,它需要一个 R 列表作为参数是我最大的绊脚石。

我已经通过使用如下的全局定义使其工作,但如果我可以将其全部包含在 Rcpp 中并且不需要全局调用,我会更愿意。

#include <math.h>
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

using namespace Rcpp;

/*** R
asim_ = function(len_, rho_, burn_in_){
  return(as.vector(arima.sim(n = len_, n.start = burn_in_, list(ar = c(rho_)))))
}
*/

// [[Rcpp::export]]
NumericVector asim_cxx(int x, double y, int z) {  
  Rcpp::Environment G = Rcpp::Environment::global_env();
  Rcpp::Function asim_ = G["asim_"];
  NumericVector out = asim_(x, y, z);
  return(out);
}

感谢所有阅读或回复的人。我希望这不是重复的。

Rcpp for everyone告诉你how to use R functions with named parameters as well as how to construct lists.

您可以将代码修改为

#include <math.h>
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

using namespace Rcpp;

// [[Rcpp::export]]
NumericVector asim_cxx(int len_, double rho_, int burn_in_) {
  Function asim_("arima.sim");
  NumericVector out = asim_(Named("n", len_),
                            Named("n.start", burn_in_),
                            List::create(Named("ar") = rho_));
  return(out);
}

假设它被保存为asim.cxx

> sourceCpp("asim.cxx")
> asim_cxx(10, 0.827, 100)
Time Series:
Start = 1 
End = 10 
Frequency = 1 
 [1]  0.7722204  1.2900218  2.1249671  0.7970526 -0.1813897  1.7879515
 [7]  1.9300430  2.6370638  1.6934178  2.0872313