The title says it.
my vector
TF <- c(F,T,T,T,F,F,T,T,F,T,F,T,T,T,T,T,T,T,F)
my desired output
[1] 0 1 2 3 0 0 1 2 0 1 0 1 2 3 4 5 6 7 0
#with(rle(TF), sequence(lengths) * rep(values, lengths))
with(rle(TF), sequence(lengths) * TF) #Like Rich suggested in comments
# [1] 0 1 2 3 0 0 1 2 0 1 0 1 2 3 4 5 6 7 0
You could use rle()
along with sequence()
.
replace(TF, TF, sequence(with(rle(TF), lengths[values])))
# [1] 0 1 2 3 0 0 1 2 0 1 0 1 2 3 4 5 6 7 0
replace()
does the coercion for us.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With