双边移动平均线?

rsk*_*k82 6 r

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

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

G. *_*eck 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)
Run Code Online (Sandbox Code Playgroud)

编辑:

请注意,由于这是写的动物园的开发版本已更改,因此,而不是写partial = TRUE一个写规则="部分"或rule = 3.问题在于,随着新的结束规则被添加到开发版本(现在有3个和第4个将在其发布之前添加),每个规则都有一个单独的参数,使用户界面变得混乱.也rule与更一致的approx在R的核心事实上,rule=1并且rule=2将具有在相同的含义rollapply和在approx(来自R的芯),用于更好的一致性和易用性.mean下面的示例中的括号目前在开发版本中是必需的,以防止它rollmean在哪里调用rule="partial" 尚未实施,但在正式发布之前,这样做的必要性将被消除.

source("http://r-forge.r-project.org/scm/viewvc.php/*checkout*/pkg/zoo/R/rollapply.R?revision=815&root=zoo")
rollapply(zoo(x), 3, (mean), rule = "partial")
Run Code Online (Sandbox Code Playgroud)


Dir*_*tel 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.
Run Code Online (Sandbox Code Playgroud)