Search code examples
rvectorlogiccumsum

Identifying positions of the last TRUEs in a sequence of TRUEs and FALSEs


I have a vector of TRUEs and FALSEs:

x <- c(F,F,F,T,T,T,F,F,F,T,T,T,F,T,T)

I'd like to elegantly (and in base) identify the position of the last TRUE before it changes to FALSE.

The following works, though, it seems like it could be simplified:

c((x[-1] != x[-length(x)]),T) & x
> FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE

Input and output: enter image description here


Solution

  • We may look where x is greater than shifted x with 0 appended.

    x>c(x[-1],0)
    # [1] FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE