Search code examples
c++rrcpparima

Simulation of AR(1) in Rcpp


Is there a way of calling arima.sim using Rcpp sugar? The fact that it need an R list as an argument has been my biggest stumbling block so far.

I've got it to work by using a global definition as below, but would much prefer if I could contain it all in Rcpp and not need global calls.

#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);
}

Thank you to anyone who reads or responds. I hope this is not a duplicate.


Solution

  • Rcpp for everyone tells you how to use R functions with named parameters as well as how to construct lists.

    You can modify your code as

    #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);
    }
    

    Assuiming it is saved as 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