【问题标题】:ACF function with rcpp带有 rcpp 的 ACF 函数
【发布时间】:2018-11-20 04:52:27
【问题描述】:

我正在尝试创建一个将样本自相关 (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。

【问题讨论】:

    标签: r rcpp


    【解决方案1】:

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

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

    这里是调整后的代码:

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

    【讨论】:

    • 你明白这运行 R 代码 因此以 R 代码的速度运行吗?从 C++ 调用它只是让你的生活变得更加困难。
    • @Dirk 这就是我想用前两句话表达的意思。也许我应该更明确一点。
    • 我知道知道。我只是想确保 OP 知道。
    • @Rafael 请参阅 Dirk 的评论,以防您根据我的回答不清楚。
    • 我明白他们想告诉我的代码不会更快。我只需要知道如何通过调用c ++来使用ACF,来制作一个更复杂的项目。
    猜你喜欢
    • 2013-11-13
    • 1970-01-01
    • 2021-04-24
    • 2019-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多