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

From: Duncan Murdoch <>
Date: Thu 03 Mar 2005 - 09:39:31 EST

On Wed, 2 Mar 2005 17:22:43 -0500, "Whit Armstrong" <> 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.

I don't know of a general purpose function, but filter() (in the stats package) can do the example you give, or any other linear filter.


x <- rnorm(1000)
y <- filter(x, rep(1,20))

puts 20 element sums into y. The vector ends up the same length as x, with NAs at the beginning and end (by default).

Duncan Murdoch mailing list PLEASE do read the posting guide! Received on Thu Mar 03 10:21:56 2005

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