[R] apply a function to a rolling subset of a vector

From: Ken Knoblauch <knoblauch_at_lyon.inserm.fr>
Date: Thu 03 Mar 2005 - 08:42:01 EST


Try this:

> ?convolve
> x<-rnorm(1000)
> y<-rep(1,20)
> z<-convolve(x,y,type="filter")
> plot(x,type="l")
> str(z)

 num [1:981] 6.31 7.28 8.16 7.39 4.65 ...
> lines(c(rep(0,10),z,rep(0,10)),col="yellow",lwd=3)
> lines(c(rep(0,10),z,rep(0,10))/length(y),col="red",lwd=3) #running mean

You wrote:
Does anyone know an easy way to calculate the rolling 20 period average or sum of a vector?

For instance:
x <- rnorm(1000)

y <- apply.subset(x,20,fun="sum")

The first element of y would contain the sum of elements 1 to 20, the second element of y
would contain the sum of elements 2:21, and so on.

I thought I had seen this on the list a year or so ago, but I couldn't find anything in the archives.

Thanks in advance,
Whit

        [[alternative HTML version deleted]]



Ken Knoblauch
Inserm U 371
Cerveau et Vision
18 avenue du Doyen Lepine
69675 Bron cedex
France
tel: +33 (0)4 72 91 34 77
fax: +33 (0)4 72 91 34 61
portable: 06 84 10 64 10

R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Thu Mar 03 10:15:17 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:30:39 EST