RCPP 中 AR(1) 的模拟.

Simulation of AR(1) in Rcpp

本文关键字:模拟 AR RCPP      更新时间:2023-10-16

有没有办法用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 告诉大家如何使用带有命名参数的 R 函数以及如何构造列表。

您可以将代码修改为

#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