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.