Sum of vector elements

2019-04-13 23:19发布

问题:

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 last positive element or the last negative element.

回答1:

Try the following:

x <- 5:-5
# sum until last positive:
sum(x[1:max(which(x > 0))])

x <- -5:5
# sum until last negative:
sum(x[1:max(which(x < 0))])

Explanation:

Which(x > 0) gives a vector of index numbers at which x is greater than 0. Taking the max of this gives the last such index. Then all that remains is summing up x from 1 up to this element. I hope this helps.



标签: r vector sum