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

Marc Schwartz MSchwartz at MedAnalytics.com
Wed Mar 2 23:45:59 CET 2005


On Wed, 2005-03-02 at 17:22 -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.

You can use the running() function in the gtools package, which is in
the gregmisc bundle:

x <- rnorm(1000)

> running(x, fun = sum, width = 20)
         1:20          2:21          3:22          4:23          5:24
 -2.009684610  -2.205737077  -1.410810606  -2.226661837  -1.684604289
         6:25          7:26          8:27          9:28         10:29
 -4.492008605  -3.816273719  -5.348364598  -6.444591766  -5.263013812
        11:30         12:31         13:32         14:33         15:34
 -4.609829115  -5.935537291  -6.909232329  -4.881021777  -5.803659103
...

See ?running for more information, after installing gregmisc from CRAN. 

HTH,

Marc Schwartz




More information about the R-help mailing list