Sequentially index between a boolean vector in R [duplicate]

半腔热情 提交于 2019-12-14 01:09:24

问题


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 

回答1:


#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



回答2:


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.




回答3:


We can use rleid

library(data.table)
ave(TF, rleid(TF), FUN = seq_along)*TF
#[1] 0 1 2 3 0 0 1 2 0 1 0 1 2 3 4 5 6 7 0



回答4:


By using base R

ave(cumsum(TF==FALSE), cumsum(TF==FALSE), FUN=seq_along)-1
 [1] 0 1 2 3 0 0 1 2 0 1 0 1 2 3 4 5 6 7 0



回答5:


You can also use inverse.seqle from cgwtools:

library(cgwtools)
SEQ = inverse.seqle(rle(TF)) 
SEQ[!TF] = 0

Or similar to @d.b's answer:

inverse.seqle(rle(TF))*TF

# [1] 0 1 2 3 0 0 1 2 0 1 0 1 2 3 4 5 6 7 0


来源:https://stackoverflow.com/questions/46477148/sequentially-index-between-a-boolean-vector-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!