Skip to content
Prev 205306 / 398506 Next

Extract vector elements until cumsum <= x

Dgnn wrote:
Your quest for "move to the next index and repeat" only makes sense when the
vector can be negative, so there might be several indexes where the crossing
occurs. However, there is an additional assumptions that there was really a
crossing; or, alternatively, that cumsum was below threshold in between.

Here is a version that uses "diff" (Check: the index might be off-by one)
Dieter



set.seed(4711)
vec = rnorm(100)
cumsum(vec)
thresh = 4
which(diff(cumsum(vec)<thresh)==1)