Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

zoo - Moving average of previous three values in R

In the zoo package there is a function called rollmean, which enables you to make moving averages. The rollmean(x,3) will take the previous, current and next value (ie 4, 6 and 2) in the table below. This is shown in the second column.

x   rollmean    ma3
4       
6   4.0 
2   4.3 
5   3.0         4.0
2   6.3         4.3
12  6.0         3.0
4   6.0         6.3
2               6.0

I would like to get the same job done, but by averaging out the previous 3 values in the fourth row. This is displayed in the third column. Can anybody tell me the name of the function that will help to accomplish this?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use rollmean, but set align='right'. Or you could use rollmeanr, which has align='right' as the default.

ma3 <- rollmeanr(x[,1],3,fill=NA)

...but you would still need to lag the result. Another solution is to use rollapply with a list for the width argument:

ma3 <- rollapplyr(x[,1],list(-(3:1)),mean,fill=NA)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...