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
To find the number of runs, we can use rle function in R that stands for Run Length Encoding.
The number of runs of a sequence is the number of increasing subsequences of the sequence.
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.
Use rle()
:
y <- rle(c(1,0,0,0,1,0,0,0,0,0,2,0,0)) y$lengths[y$values==0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With