[R] Running sum

Marc Schwartz MSchwartz at MedAnalytics.com
Fri Nov 19 22:42:01 CET 2004


On Fri, 2004-11-19 at 21:10 +0100, Philippe Grosjean wrote:
> ?cumsum is not exactly the answer (as I understand it), but a part of it.
> I propose:
> 
> runSum2 <- function(x)
> 	cumsum(x)[-1] - c(0, cumsum(x[1:(length(x) - 2)]))
> 
> # Example
> a <- round(runif(10, 0, 10))
> a
> runSum2(a)
> max(runSum2(a)) # To get only the max


Phillipe, 

If you run Sean's original function for 1:10, you get:

X <- 1:10
Y <- vector(length = 10)
Y[1] <- X[1]

for (i in 2:10)
{
   Y[i] <- Y[i-1] + X[i]
}

> Y
 [1]  1  3  6 10 15 21 28 36 45 55

which is equivalent to cumsum(1:10)


Your function yields:

> runSum2(1:10)
[1]  3  5  7  9 11 13 15 17 19

Which is the sum of successive individual pairs of vector elements.

For future reference, the running() function in the gregmisc bundle's
gtools package offers a more general approach to 'moving window'
functions:

> running(1:10, width = 2, fun = sum)
 1:2  2:3  3:4  4:5  5:6  6:7  7:8  8:9 9:10 
   3    5    7    9   11   13   15   17   19 


Best regards,

Marc Schwartz




More information about the R-help mailing list