我使用滚动加权移动平均函数,其代码如下所示.它通过Rcpp用C++编写.此功能适用于大多数时间系列,没有循环问题或类似的东西.我在下面提供了一系列长度为2的系列,有时会触发致命错误.我找不到错误的原因.
谢谢你的帮助!=)
这是R代码:
# Install packages
sourceCpp("partialMA.cpp")
spencer_weights=c( -3, -6, -5, 3, 21, 46, 67, 0, 67, 46, 21, 3, -5, -6, -3)
spencer_ma <- function(x) roll_mean(x,spencer_weights)
x=c(11.026420323685528,0.25933761651337001)
spencer_ma(x) # works
for(i in 1:1000) spencer_ma(x) # triggers the fatal error
Run Code Online (Sandbox Code Playgroud)
我在下面包含了我的roll_mean函数的C++代码:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector roll_mean(const NumericVector& x,
const NumericVector& w) {
int n = x.size();
int w_size = w.size();
int size = (w_size - 1) / 2;
NumericVector res(n);
int i, ind_x, ind_w;
double w_sum …Run Code Online (Sandbox Code Playgroud)