双边移动平均线?

时间:2010-12-11 19:54:54

标签: r

如何获得双向“移动平均线”,这是一个从向量的左右平均n个数字并根据它们与中心值的距离给出权重的函数?

我尝试使用TTR,但其移动平均线仅从左到右工作,并将最左边的值设置为NA。所以我不能使用平滑的矢量作为smooth.spline的输入

3 个答案:

答案 0 :(得分:9)

在动物园包中rollmeanrollapply的参数允许多种变化。

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=1rule=2rollapply和{{{}}中的含义相同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)

您可以与kernel一起试用kernapply(第一页末尾有一些示例)。