Question

I have a binary vector and I want to count how many sequences of 1's I've got. So that if I have a vector like:

bin <- c(1,1,0,1,1,1,1,0,0,0,1,0,1,1,0,0,1,1,1)

I would get 5. I haven't found any existing functions that could do this, anyone got any good tips on how one could write one? I don't know how to build the "counter" when the sequences all have different lengths.

Était-ce utile?

La solution

The run length encoding function (rle) is built for this. Helpfully whilst it computes the length of runs of equal values in a vector, it returns those lengths with the values. So use rle( bin ).

Compare the $values output to your desired value (1) with == and sum the result (because you get a TRUE or 1L when the run of values is of 1's):

sum( rle(bin)$values == 1 )
[1] 5
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top