Find the *first* longest sequence of TRUE in a boolean vector

One option could be:

with(rle(bool), rep(seq_along(values) == which.max(lengths * values), lengths))

Results for the first vector:

[1] FALSE  TRUE FALSE FALSE

For the second:

[1] FALSE FALSE FALSE  TRUE  TRUE

For the third:

[1] FALSE  TRUE  TRUE FALSE FALSE FALSE

Not elegant but might work:

bool <- c(FALSE, TRUE, FALSE, TRUE)

tt <- rle(bool)
t1 <- which.max(tt$lengths[tt$values])
tt$values[tt$values][-t1] <- FALSE
inverse.rle(tt)
#[1] FALSE  TRUE FALSE FALSE

and as a function:

fun <- function(bool) {
  tt <- rle(bool)
  t1 <- which.max(tt$lengths[tt$values])
  tt$values[tt$values][-t1] <- FALSE
  inverse.rle(tt)
}
fun(c(FALSE, TRUE, FALSE, TRUE))
#[1] FALSE  TRUE FALSE FALSE

fun(c(FALSE, TRUE, FALSE, TRUE, TRUE))
#[1] FALSE FALSE FALSE  TRUE  TRUE

fun(c(FALSE, TRUE, TRUE, FALSE, TRUE, TRUE))
#[1] FALSE  TRUE  TRUE FALSE FALSE FALSE

fun(FALSE)
#[1] FALSE

fun(logical(0))
#logical(0)

Tags:

R