How can I count runs in a sequence?

count, r

Solution

Use `rle()`:

y <- rle(c(1,0,0,0,1,0,0,0,0,0,2,0,0))
y$lengths[y$values==0]

Problem

In R, what would be the most efficient/simplest way to count runs of identical elements in a sequence? For example, how to count the numbers of consecutive zeros in a sequence of non-negative integers: ``` x <- c(1,0,0,0,1,0,0,0,0,0,2,0,0) # should give 3,5,2 ```

Original source