【问题标题】:Cumulative sums, moving averages, and SQL "group by" equivalents in RR中的累积和、移动平均线和SQL“分组依据”等价物
【发布时间】:2010-11-13 06:03:45
【问题描述】:

在 R 中创建移动平均线或滚动和的最有效方法是什么?滚动功能和“分组依据”如何实现?

【问题讨论】:

    标签: r average time-series moving-average


    【解决方案1】:

    虽然动物园很棒,但有时也有更简单的方法。如果您的数据表现良好并且间隔均匀,则 embed() 函数可以有效地让您创建时间序列的多个滞后版本。如果你在 VARS 包内部查看向量自回归,你会看到包作者选择了这条路线。

    例如,计算 x 的 3 个周期的滚动平均值,其中 x = (1 -> 20)^2:

    > x <- (1:20)^2
    > embed (x, 3)
          [,1] [,2] [,3]
     [1,]    9    4    1
     [2,]   16    9    4
     [3,]   25   16    9
     [4,]   36   25   16
     [5,]   49   36   25
     [6,]   64   49   36
     [7,]   81   64   49
     [8,]  100   81   64
     [9,]  121  100   81
    [10,]  144  121  100
    [11,]  169  144  121
    [12,]  196  169  144
    [13,]  225  196  169
    [14,]  256  225  196
    [15,]  289  256  225
    [16,]  324  289  256
    [17,]  361  324  289
    [18,]  400  361  324
    > apply (embed (x, 3), 1, mean)
     [1]   4.666667   9.666667  16.666667  25.666667  36.666667  49.666667
     [7]  64.666667  81.666667 100.666667 121.666667 144.666667 169.666667
    [13] 196.666667 225.666667 256.666667 289.666667 324.666667 361.666667
    

    【讨论】:

      【解决方案2】:

      我在 r 列表中从 Achim Zeileis 那里找到了一个很好的答案。他是这样说的:

      library(zoo)
      ## create data
      
      x <- rnorm(365)
      ## transform to regular zoo series with "Date" index
      
      x <- zooreg(x, start = as.Date("2004-01-01")) plot(x)
      
      ## add rolling/running/moving average with window size 7 
      
      lines(rollmean(x, 7), col = 2, lwd = 2)
      
      ## if you don't want the rolling mean but rather a weekly ## time series of means you can do
      nextfri <- function(x) 7 * ceiling(as.numeric(x - 1)/7) + as.Date(1) xw <- aggregate(x, nextfri, mean)
      
      ## nextfri is a function which computes for a certain "Date" ## the next friday. xw is then the weekly series. 
      
      lines(xw, col = 4)
      

      阿奇姆接着说:

      请注意,两者之间的区别是 滚动平均值和聚合序列 是因为对齐方式不同。这 可以通过更改“对齐”来更改 rollmean() 中的参数或 nextfri() 函数聚合 称呼。

      这一切都来自阿奇姆,而不是来自我: http://tolstoy.newcastle.edu.au/R/help/05/06/6785.html

      【讨论】:

        猜你喜欢
        • 2023-03-09
        • 1970-01-01
        • 2016-05-16
        • 2020-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多