An embedded and charset-unspecified text was scrubbed... Name: not available Url: https://stat.ethz.ch/pipermail/r-help/attachments/20050302/331d8b6f/attachment.pl
apply a function to a rolling subset of a vector
4 messages · Whit Armstrong, Duncan Murdoch, Marc Schwartz +1 more
On Wed, 2 Mar 2005 17:22:43 -0500, "Whit Armstrong" <whit at twinfieldscapital.com> 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. e.g. 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
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
Whit Armstrong <whit <at> twinfieldscapital.com> writes: : : 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. : Look at ?filter . Also ?embed and gtools::running . filter is the fastest.