使用rcpp进行ACF功能

时间:2018-06-11 00:36:16

标签: r rcpp

我正在尝试创建一个将样本自相关(ACF)添加到固定滞后的函数。我不太了解c ++的语法,知道如何解决这个错误。

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

预期产量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

注意:该功能不应显示情节,应处理缺失值NA。

1 个答案:

答案 0 :(得分:2)

我希望你真正的C ++函数不仅仅是回调R,否则这没有意义。无论如何:

    C ++和R中的
  • NULL是不同的。使用Rcpp::Nullable<T>
  • 如果R函数具有您要指定的默认参数,则必须按正确的顺序执行此操作。
  • [[在R和C ++中有不同的含义。
  • List返回sum时,为什么要返回double

这里是经过调整的代码:

#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)
*/