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

Kha*_*nes 10 logic r vector cumsum

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)
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

Input and output: 在此处输入图片说明

the*_*ail 9

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
Run Code Online (Sandbox Code Playgroud)

  • 更多高尔夫球`diff(c(x,0))&lt;0`。 (3认同)

jay*_*.sf 6

我们不妨来看看其中x大于转移x0追加。

x>c(x[-1],0)
# [1] FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE
Run Code Online (Sandbox Code Playgroud)


WeN*_*Ben 5

查看 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
Run Code Online (Sandbox Code Playgroud)

弗兰克建议的另一种布局

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
Run Code Online (Sandbox Code Playgroud)