[R] Sum of vector elements

R. Michael Weylandt michael.weylandt at gmail.com
Tue Aug 7 18:00:54 CEST 2012


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.



More information about the R-help mailing list