带有 rcpp 的 ACF 函数
ACF function with 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。
我希望你真正的 C++ 函数不仅仅是回调 R。否则这没有意义。不管怎样:
NULL
在 C++ 和 R 中是不同的。使用 Rcpp::Nullable<T>
- 如果 R 函数具有您要指定的默认参数,则必须以正确的顺序执行此操作。
[[
在R和C++中有不同的含义。
- 为什么在
sum
returns 返回 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)
*/
我正在尝试创建一个将样本自相关 (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。
我希望你真正的 C++ 函数不仅仅是回调 R。否则这没有意义。不管怎样:
NULL
在 C++ 和 R 中是不同的。使用Rcpp::Nullable<T>
- 如果 R 函数具有您要指定的默认参数,则必须以正确的顺序执行此操作。
[[
在R和C++中有不同的含义。- 为什么在
sum
returns 返回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)
*/