Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count consecutive elements in a same length vector

If I have a vector like

"a": 0 0 1 1 1 0 0 0 0 1 1 0 0 0

How can I generate a vector of the same length containing the count of consecutive elements, like so:

"b": 2 2 3 3 3 4 4 4 4 2 2 3 3 3

I tried rle, but I did not manage to stretch it out this way.

like image 512
Cos Avatar asked Jan 07 '19 10:01

Cos


1 Answers

Another option using rle and rep

with(rle(a), rep(lengths, times = lengths))
# [1] 2 2 3 3 3 4 4 4 4 2 2 3 3 3

data

a <- c(0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0)
like image 182
markus Avatar answered Sep 28 '22 10:09

markus