[R] Consecutive zeros in a vector
Duncan Murdoch
murdoch at stats.uwo.ca
Tue Apr 29 17:46:23 CEST 2008
On 29/04/2008 11:39 AM, Kenn Konstabel wrote:
> Suppose X is a long vector of integers (typically about 30000 elements). Is
> there an efficient way to detect whether there are at least N consecutive
> zeros in X, and if yes, where does this occur?
>
> for example, suppose X is:
> ...
>
> and N is 10. I would like a foo(X, 10) to return something like c(6,19)
> (start and end positions in X of at least 10 consecutive zeros). I can think
> of a number of slow and probably inefficient ways of doing it (nested
> loops..), but perhaps someone has a better idea..
Something based on rle() should be fairly easy. rle(x)$lengths > 9
identifies the long runs, cumsum(rle(x)$lengths) identifies where runs end.
Duncan Murdoch
More information about the R-help
mailing list