Skip to content
Prev 302590 / 398503 Next

Sum of vector elements

Another approach... not exactly more direct, but perhaps more robust and more general:

tmp <- aggregate(x,list(lvl=cumsum(abs(diff(c(FALSE,x>0))))), FUN=sum)
ans <- tmp[0==tmp$lvl,"x"]

abs(diff()) finds transitions, FALSE forces level zero to represent negative numbers
cumsum marks levels (groups of positive and not-positive numbers)
aggregate does the summation
ans may be empty if x started with positive numbers.
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
--------------------------------------------------------------------------- 
Sent from my phone. Please excuse my brevity.
"R. Michael Weylandt" <michael.weylandt at gmail.com> wrote: