Yu *_*eng 7 signals r time-series filter na
我试图实现Chebyshev过滤器以平滑时间序列但不幸的是,数据系列中有NA.
例如,
t <- seq(0, 1, len = 100)
x <- c(sin(2*pi*t*2.3) + 0.25*rnorm(length(t)),NA, cos(2*pi*t*2.3) + 0.25*rnorm(length(t)))
Run Code Online (Sandbox Code Playgroud)
我正在使用Chebyshev过滤器: cf1 = cheby1(5, 3, 1/44, type = "low")
我试图过滤排除NAs的时间序列,但不会弄乱订单/位置.所以,我已经尝试过na.rm=T
,但似乎没有这样的论点.然后
z <- filter(cf1, x) # apply filter
Run Code Online (Sandbox Code Playgroud)
感谢你们.
您可以使用该功能预先删除 NA compelete.cases
。您还可以考虑估算缺失的数据。查看 mtsdi 或 Amelia II 软件包。
编辑:
这是 Rcpp 的解决方案。如果速度很重要,这可能会有所帮助:
require(inline)
require(Rcpp)
t <- seq(0, 1, len = 100)
set.seed(7337)
x <- c(sin(2*pi*t*2.3) + 0.25*rnorm(length(t)),NA, cos(2*pi*t*2.3) + 0.25*rnorm(length(t)))
NAs <- x
x2 <- x[!is.na(x)]
#do something to x2
src <- '
Rcpp::NumericVector vecX(vx);
Rcpp::NumericVector vecNA(vNA);
int j = 0; //counter for vx
for (int i=0;i<vecNA.size();i++) {
if (!(R_IsNA(vecNA[i]))) {
//replace and update j
vecNA[i] = vecX[j];
j++;
}
}
return Rcpp::wrap(vecNA);
'
fun <- cxxfunction(signature(vx="numeric",
vNA="numeric"),
src,plugin="Rcpp")
if (identical(x,fun(x2,NAs)))
print("worked")
# [1] "worked"
Run Code Online (Sandbox Code Playgroud)