Count sequences of 1 within vector in R

Asked

Viewed 514 times

8

I would like to know how to count sequences of 1 within a vector containing only 0 and 1. For example, in the vector x <- c(1, 1, 0, 0, 1, 0, 1, 1), the count would give the vector (2, 1, 2), which counts the sequence of 2 "1", 1 "1" and finally 2 "1".

1 answer

10


The function rle is perfect for this. It counts exactly the number of lengths and sequence values in a vector:

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

Even, although this was not requested in the original question, this function could have been used to count the sequence sizes of "0":

contagem$lengths[contagem$values==0]
[1] 2 1

For more information, use the command ?rle.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.