Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequentially index between a boolean vector in R [duplicate]

Tags:

r

seq

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 
like image 210
Maxwell Chandler Avatar asked Dec 02 '22 11:12

Maxwell Chandler


2 Answers

#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
like image 145
d.b Avatar answered Dec 04 '22 13:12

d.b


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.

like image 38
Rich Scriven Avatar answered Dec 04 '22 12:12

Rich Scriven