[R] Extract vector elements until cumsum <= x

Dieter Menne dieter.menne at menne-biomed.de
Mon Jan 4 11:10:15 CET 2010




Dgnn wrote:
> 
> 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.
> 
> 

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)






-- 
View this message in context: http://n4.nabble.com/Extract-vector-elements-until-cumsum-x-tp998023p998155.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list