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