[R] Running sum

Marc Schwartz MSchwartz at MedAnalytics.com
Fri Nov 19 19:57:24 CET 2004


On Fri, 2004-11-19 at 13:08 -0500, Sean Davis wrote:
> I have vector X of length N that I want to have a running sum for 
> (called Y).  I just need max(Y).  I do this with a "for" loop like so:
> 
>      Y <- vector(length=N)
>      Y[1] <- X[1]
>      for (i in 2:N) {
>        Y[i] <- Y[i-1]+X[i]
>      }
>      return(max(Y))
> 
> Is there a faster way to do this?
> 
> Thanks,
> Sean


Something like:

> cumsum(1:10)
 [1]  1  3  6 10 15 21 28 36 45 55

> max(cumsum(1:10))
[1] 55

Does that help?

Marc Schwartz




More information about the R-help mailing list