【问题标题】:two-sided moving average?双边移动平均线?
【发布时间】:2010-12-11 19:54:54
【问题描述】:

如何获得双边“移动平均线”,它是一个函数,对向量的左右 n 个数字进行平均,并根据它们与中心值的距离赋予它们权重?

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

【问题讨论】:

    标签: r


    【解决方案1】:

    在 zoo 包中,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)
    

    编辑:

    请注意,由于这是编写的,因此 Zoo 的开发版本已更改,而不是编写 partial = TRUE,而是编写 rule = "partial" 或 rule = 3。问题是,随着新的结束规则被添加到开发版本(现在有 3 个,并且在发布之前将添加第 4 个),每个规则都有一个单独的参数,使用户界面混乱。此外,rule 与 R 核心中的 approx 更一致。事实上,rule=1rule=2rollapplyapprox(来自 R 的核心)中具有相同的含义(来自 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")
    

    【讨论】:

    • 但是为什么rollmean的输出总是比itput短一个元素呢?
    【解决方案2】:

    查看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.
    

    【讨论】:

      【解决方案3】:

      你可以试试kernelkernapply(第一页末尾有一些例子)。

      【讨论】:

        猜你喜欢
        • 2017-09-01
        • 2013-12-22
        • 2022-01-26
        • 1970-01-01
        • 2011-07-28
        • 2011-06-29
        • 2019-04-24
        • 2012-05-24
        • 2021-01-18
        相关资源
        最近更新 更多