Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count runs in a sequence?

Tags:

r

count

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 
like image 245
andrekos Avatar asked Oct 01 '09 09:10

andrekos


People also ask

How do you find the number of runs in a sequence?

To find the number of runs, we can use rle function in R that stands for Run Length Encoding.

How many runs are in a sequence?

The number of runs of a sequence is the number of increasing subsequences of the sequence.

How do you count runs?

Divide the rise by the slope to calculate the run. In the example, if you had a rise of 12, divide by 0.6 to calculate a run of 20.


1 Answers

Use rle():

y <- rle(c(1,0,0,0,1,0,0,0,0,0,2,0,0)) y$lengths[y$values==0] 
like image 66
Rob Hyndman Avatar answered Nov 06 '22 13:11

Rob Hyndman