質問

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

他のヒント

私は、rリストにアヒム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/ヘルプ/ 05/06 / 6785.htmlする

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top