[R] Sum of vector elements

Jeff Newmiller jdnewmil at dcn.davis.CA.us
Tue Aug 7 19:25:00 CEST 2012


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:

>I'd do something like this:
>
>x <- sample(seq(-10, 10))
>
>sum(x[seq_len(which.max(x > 0)])
>
>Though others might have more direct solutions.
>
>which.max() gets you the index of the first time x > 0 -- seq_len
>gives you numbers 1 to that index -- then just subset and sum like
>normal.
>
>Best,
>Michael
>
>On Tue, Aug 7, 2012 at 7:37 AM, number10 <havana_dream at ymail.com>
>wrote:
>> Hi, Is it possible to avoid using do and while loops to calculate the
>sum of
>> the elements of a vector until the appearance of the first positive
>element.
>>
>>
>>
>> --
>> View this message in context:
>http://r.789695.n4.nabble.com/Sum-of-vector-elements-tp4639395.html
>> Sent from the R help mailing list archive at Nabble.com.
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>
>______________________________________________
>R-help at r-project.org mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide
>http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list