Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving average with varying time window in R

Tags:

r

I want to compute a moving average over a certain time window without generating NAs at the beginning of the time series. For instance, if I set the time window to 3, the 2 first observations will have NAs. What I want is to have a time window of 1 for the first observation, 2 for the second observation, and then 3 for all the remaining observations.

My current code:

#example data
x <- c(3,9,2,8,4,6,5,8)
#moving average with time window of length 3
(ma3 <- filter(x,rep(1/3,3),sides=1))
like image 491
cwarny Avatar asked Feb 17 '13 21:02

cwarny


2 Answers

I don't see a way other than brute-force:

Using rollapply from package zoo instead of filter:

c(x[1], mean(x[1:2]), rollapply(x, width=3, FUN=mean))
like image 68
Matthew Lundberg Avatar answered Sep 24 '22 02:09

Matthew Lundberg


Let me jump on the rollapply train, too:

> rollapply(c(NA, NA, x), width=3, FUN=mean, na.rm=T)
[1] 3.000000 6.000000 4.666667 6.333333 4.666667 6.000000 5.000000 6.333333

Prepending two = 3-1 NA values and using na.rm=T has the effect of extending the time series but ignoring the new values for calculating the mean. A slightly more difficult but otherwise equivalent syntax

> rollapply(c(NA, NA, x), width=3, FUN=function(v) mean(v, na.rm=T))

Thanks to Matthew for pointing this out.

like image 24
krlmlr Avatar answered Sep 25 '22 02:09

krlmlr