Finds the Longest Stretch of Consecutive TRUE Values in a Logical Vector
Source:R/graph_MS_cx.R
find.longest.true.stretch.RdThis function takes a logical vector as input and returns the starting index and length of the longest sub-interval where the values are TRUE.
Value
A list with two elements:
- start_index
The index at which the longest stretch of consecutive TRUE values starts.
- length
The length of the longest stretch of consecutive TRUE values.
Note
If there are multiple disjoined stretch of TRUE values of the same length, then the first one is returned.
Examples
l <- c(TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE)
result <- find.longest.true.stretch(l)
print(result)
# $start_index
# [1] 4
# $length
# [1] 3
## Two longest TRUE stretches
l <- c(TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE)
find.longest.true.stretch(l)
# $start.index
# [1] 1
# $length
# [1] 3
## No TRUE values
l <- c(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE)
find.longest.true.stretch(l)
# $start.index
# [1] NA
# $length
# [1] 0