代码之家  ›  专栏  ›  技术社区  ›  Rafael Díaz

带RCPP的ACF功能

  •  0
  • Rafael Díaz  · 技术社区  · 7 年前

    我试图创建一个函数,将样本自相关(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 回复  |  直到 7 年前
        1
  •  2
  •   Ralf Stubner    7 年前

    我希望你真正的C++功能不仅仅是调用R,否则这毫无意义。无论如何:

    • NULL 在C++和R中是不同的。使用 Rcpp::Nullable<T>
    • 如果r函数有要指定的默认参数,则必须按正确的顺序执行此操作。
    • [[ 在R和C++中有不同的含义。
    • 你为什么要回一个 List 什么时候 sum 返回A 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)
    */