[R] Running sum
Philippe Grosjean
phgrosjean at sciviews.org
Fri Nov 19 21:10:37 CET 2004
?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
Best,
Philippe
..............................................<°}))><........
) ) ) ) )
( ( ( ( ( Prof. Philippe Grosjean
) ) ) ) )
( ( ( ( ( Numerical Ecology of Aquatic Systems
) ) ) ) ) Mons-Hainaut University, Pentagone
( ( ( ( ( Academie Universitaire Wallonie-Bruxelles
) ) ) ) ) 6, av du Champ de Mars, 7000 Mons, Belgium
( ( ( ( (
) ) ) ) ) phone: + 32.65.37.34.97, fax: + 32.65.37.33.12
( ( ( ( ( email: Philippe.Grosjean at umh.ac.be
) ) ) ) )
( ( ( ( ( web: http://www.umh.ac.be/~econum
) ) ) ) )
..............................................................
> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch
> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Marc Schwartz
> Sent: Friday, November 19, 2004 7:57 PM
> To: Sean Davis
> Cc: R-Help
> Subject: Re: [R] Running sum
>
> 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
>
> ______________________________________________
> 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
>
>
More information about the R-help
mailing list