Skip to content

Extract vector elements until cumsum <= x

5 messages · Dgnn, Dieter Menne, Gabor Grothendieck

#
Hi All,

I have a vector n, and for each n[i] I want to extract n[i], n[i+1],
n[i+2]..., until the cumulative sum of n[i] and subsequent elements exceeds
a CheckValue, whereupon I move to the next index and repeat. 

I am trying to find a Vectorized approach, and have seen similar posts where
filter{stat} and rollmean{zoo} were suggested, but, I haven't been able to
figure a way to use them for this problem.

Best wishes to all, and thanks for the help!

Dgnn
#
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)
#
Try this which uses 10 as the check value:

f <- function(acc, x) if (acc + x > 10) x else acc + x
x <- c(4, 6, 2, 7, 4, 1, 4, 8)
Reduce(f, x)
On Sun, Jan 3, 2010 at 10:02 PM, Dgnn <sharkbrainpdx at gmail.com> wrote:
#
Thanks a lot, everybody!
I've been working with these data for a while, and didn't realize that some
of my assumptions lead me to leave out some important info. Specifically,
that the vector contains time values of intervals between adjacent events,
and so are always positive.

Thanks again for your help

Dgnn
#
Mark Leeds pointed out to me that the last line should have been:

Reduce(f, x, accumulate = TRUE)

On Mon, Jan 4, 2010 at 8:43 AM, Gabor Grothendieck
<ggrothendieck at gmail.com> wrote: