More elegant way to return a sequence of numbers based on booleans?

前端 未结 3 1968
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-30 09:28

Here\'s a sample of booleans I have as part of a data.frame:

atest <- c(FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, TRUE,

3条回答
  •  伪装坚强ぢ
    2020-12-30 09:43

    Here's one way to do it, using handy (but not widely-known/used) base functions:

    > sequence(tabulate(cumsum(!atest)))
     [1]  1  2  3  4  5  6  7  8  9 10  1  2  3  4  5  6  7  8  9 10  1
    

    To break it down:

    > # return/repeat integer for each FALSE
    > cumsum(!atest)
     [1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3
    > # count the number of occurrences of each integer
    > tabulate(cumsum(!atest))
    [1] 10 10  1
    > # create concatenated seq_len for each integer
    > sequence(tabulate(cumsum(!atest)))
     [1]  1  2  3  4  5  6  7  8  9 10  1  2  3  4  5  6  7  8  9 10  1
    

提交回复
热议问题