sum - Summing Vector elements until a Positive element is encountered - R -
i'm new r , i'm looking through book called "discovering statistics using r". although book implies don't need statistical background, of content isn't covered/explained...
i'm trying sum elements of vector starting position 1 until positive element present.
i found this question similar i'm trying achieve. when implement it, doesn't seem work (and appears include first positive element)...
my program is:
veca <- runif(10, -10, 10); suma <-sum(veca [1:min(which(veca < 0))]);
is there more robust way calculate without using loops works every time , doesn't add positive element? i'm not @ looping stage of books yet.
i found this site asks similar question answer errors:
sum(veca [seq_len(which.max(veca > 0)]);
you want use > not < sum elements until first positive 1 reached.
you're summing 1 until first negative value reached (including first negative value).
sum(veca[1:min(which(veca>0))-1])
the which() function return of positions of positive elements, taking sum 1 position of first positive - 1 guarantee summing of negative elements
Comments
Post a Comment