Rafael Díaz
Rafael Díaz

Reputation: 2289

ACF function with rcpp

I am trying to create a function that adds the sample autocorrelations (ACF) to a fixed lag. I do not know much about the syntax of c ++, any idea of how to solve this error.

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
List acfC(NumericVector x, bool plot = true, int lagmax = NULL) {
  Environment stats("package:stats");
  Function ri=stats["acf"];
  List result =  sum(ri(x)[[1]]);
  return(result);
}

Expected output 3.579

/*** R
acfC(y,lagmax = 10,plot = F)

set.seed(1)
y = c(arima.sim(model = list(ar = 0.7), n = 200),NA)
res = acf(y, lag.max = 10,plot = F, na.action = na.pass)
sum(res$acf)
*/
[1] 3.579344

Note: The function should not show the plot and should handle missing values NA.

Upvotes: 0

Views: 168

Answers (1)

Ralf Stubner
Ralf Stubner

Reputation: 26833

I hope your real C++ function does more than calling back to R. Otherwise this makes no sense. Anyway:

  • NULL in C++ and in R are different. Use Rcpp::Nullable<T>
  • If a R function has default arguments you want to specify, you have to do this in the correct order.
  • [[ has a different meaning in R and C++.
  • Why are you returning a List when sum returns a double?

Here the adjusted code:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double acfC(NumericVector x, bool plot = true, Nullable<int> lagmax = R_NilValue) {
  Environment stats("package:stats");
  Function ri = stats["acf"];
  Function na_pass = stats["na.pass"];
  List result =  ri(x, lagmax, "correlation", plot, na_pass);
  NumericVector acf = result["acf"];
  return(sum(acf));
}

/*** R
set.seed(1)
y = c(arima.sim(model = list(ar = 0.7), n = 200),NA)
acfC(y,lagmax = 10,plot = F)


res = acf(y, lag.max = 10,plot = F, na.action = na.pass)
sum(res$acf)
*/

Upvotes: 2

Related Questions