如何获得双向“移动平均线”,这是一个从向量的左右平均n个数字并根据它们与中心值的距离给出权重的函数?
我尝试使用TTR,但其移动平均线仅从左到右工作,并将最左边的值设置为NA。所以我不能使用平滑的矢量作为smooth.spline的输入
答案 0 :(得分:9)
在动物园包中rollmean
和rollapply
的参数允许多种变化。
library(zoo)
x <- seq(10)^2
# no NAs at end
rollmean(x, 3)
# NAs at ends
rollmean(x, 3, na.pad = TRUE)
# weighted mean
rollapply(zoo(x), 3, function(x) c(1, 2, 1) %*% x / 4)
# at ends take means of less than 3 points - needs devel version
# partial= is in development and at this point must use na.rm = TRUE to use partial
source("http://r-forge.r-project.org/scm/viewvc.php/*checkout*/pkg/zoo/R/rollapply.R?revision=802&root=zoo")
rollapply(zoo(x), 3, mean, partial = TRUE, na.rm = TRUE)
编辑:
请注意,由于这是写的,因此动态园的开发版本已更改,因此不是写partial = TRUE
,而是写一个rule =“partial”或rule = 3
。问题在于,随着新的结束规则被添加到开发版本(现在有3个和第4个将在其发布之前添加),每个规则都有一个单独的参数,使用户界面变得混乱。此外,rule
与R核心中的approx
更为一致。事实上,rule=1
和rule=2
在rollapply
和{{{}}中的含义相同1}}(来自R的核心),以获得更好的一致性和易用性。以下示例中approx
周围的括号目前在开发版本中是必需的,以防止它调用mean
,其中rollmean
尚未实施,但需要这样做在正式发布时被淘汰。
rule="partial"
答案 1 :(得分:6)
查看filter()
函数,尤其是sides
参数:
filter package:stats R Documentation Linear Filtering on a Time Series Description: Applies linear filtering to a univariate time series or to each series separately of a multivariate time series. Usage: filter(x, filter, method = c("convolution", "recursive"), sides = 2, circular = FALSE, init) Arguments: [...] sides: for convolution filters only. If ‘sides=1’ the filter coefficients are for past values only; if ‘sides=2’ they are centred around lag 0. In this case the length of the filter should be odd, but if it is even, more of the filter is forward in time than backward.
答案 2 :(得分:2)