[R] Running sum

Spencer Graves spencer.graves at pdf.com
Fri Nov 19 20:00:38 CET 2004


      Have you considered "cumsum"? 

      > cumsum(c(1, 2, 3, -9, 2))
      [1]  1  3  6 -3 -1

      hope this helps.  spencer graves

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
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html


-- 
Spencer Graves, PhD, Senior Development Engineer
O:  (408)938-4420;  mobile:  (408)655-4567




More information about the R-help mailing list