Count sequences of 1 within vector in R

8

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

    
asked by anonymous 12.11.2017 / 01:24

1 answer

10

The rle function is perfect for this. It counts exactly the number of sequence lengths and 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 though this was not asked for in the original question, this function could have been used to count the sequences sizes of "0":

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

For more information, use the ?rle command.

    
12.11.2017 / 01:59