How to count sequences of ones in a logical vector

  • A+
Category:Languages

I have a logical vector like

as.logical(c(0,0,1,1,1,0,1,1,0,0,0,1,1,1,1)) 

but much longer. How can i transform it to:

c(0,0,1,2,3,0,1,2,0,0,0,1,2,3,4) 

by counting the length of ones?

 


Another rle option:

r <- rle(x) x[x] <- sequence(r$l[r$v]) #[1] 0 0 1 2 3 0 1 2 0 0 0 1 2 3 4 

Or without saving r:

x[x] <- sequence(with(rle(x), lengths[values])) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: