Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 748
Khaynes Avatar asked Jun 29 '19 02:06

Khaynes


Video Answer


4 Answers

Check rle

rlex = rle(x)
end = cumsum(rlex$lengths)
x&(seq(length(x)) %in% end)
[1] FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE

Another layout suggested by Frank

seq_along(x) %in% with(rle(x), cumsum(lengths)[values])
[1] FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE
like image 172
BENY Avatar answered Nov 11 '22 18:11

BENY


Taking advantage of diff with an appended FALSE to catch the implied TRUE-to-FALSE at the end.

diff(c(x,FALSE)) == -1
# [1] FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE  TRUE
#[13] FALSE FALSE  TRUE
like image 45
thelatemail Avatar answered Nov 11 '22 19:11

thelatemail


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
like image 35
jay.sf Avatar answered Nov 11 '22 19:11

jay.sf


Another version with rle

x[setdiff(seq_along(x), with(rle(x), cumsum(lengths) * values))] <- FALSE
x
#[1] FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE
like image 32
Ronak Shah Avatar answered Nov 11 '22 18:11

Ronak Shah