什么是创建中的R的移动平均值或滚动总和的最有效的方法是什么?你怎么用“按组”一起做滚动功能?

有帮助吗?

解决方案

虽然动物园是很大的,有时也有更简单的方法。如果数据表现很好,而且间隔均匀,嵌入()函数有效地让你创建一个时间序列的多个版本滞后。如果你看看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

其他提示

我划了从阿希姆Zeileis一个很好的答案相对于R名单上。以下是他说:

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/帮助/ 05/06 / 6785.html

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top