The filter function in the ts library handles this and quite a bit more.
library(ts) help(filter)
filter(y,rep(1,12),method="convolution",sides=1)[-(1:11)]
will give your example. (The [-(1:11)] drops initial NAs) Reid Huntsinger -----Original Message----- From: Erin Hodgess [mailto:hodgess at uhddx01.dt.uh.edu] Sent: Friday, February 22, 2002 2:10 PM To: r-help at stat.math.ethz.ch Subject: [R] Cent. Mov. Ave Dear R People: Here is an interesting question(I think) Suppose I want to calculate Centered Moving Averages; i.e. x[1] <- ( sum(y[1:12]) )/12 x[2] <- ( sum(y[2:13]) )/12 and so on. Of course, this is easily done through loops. However, I have been trying to do this more elegantly, but have failed. I have tried things like j1 <- 1:109 j2 <- 12:120 x[1:109] <- ( sum( y[j1:j2]) )/12 but it doesn't work. (Surprise!) R 1.4.0 on windows. Any ideas would be much appreciated! Thanks! Sincerely, Erin Hodgess Associate Professor Department of Computer and Mathematical Sciences University of Houston - Downtown 1 Main Street Houston, TX 77002 mailto: hodgess at uhddx01.dt.uh.edu -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. -.- r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html Send "info", "help", or "[un]subscribe" (in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._. _._ -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.- r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html Send "info", "help", or "[un]subscribe" (in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._