I've got a data like below:
library(dplyr)
ex <- data.frame(bool = c(rep(FALSE, 2), rep(TRUE, 3), rep(FALSE, 2), rep(TRUE, 5),
FALSE, FALSE, rep(TRUE, 6), FALSE, FALSE, FALSE)) %>%
mutate(seq = data.table::rleid(bool)) %>%
group_by(seq) %>%
mutate(n = n()) %>%
ungroup() %>%
mutate(expected_output = c(4, 4, NA, NA, NA, 4, 4, rep(NA,5), 4, 4, rep(NA, 6), rep(6, 3)))
For every FALSE I need to find a latest sequence of TRUE with length at least of 4. But if there's no such a sequence before (like for rows 1:2 or 6:7), we should check forward, i.e. find the first sequence of length 4 or more that appears after the observation.
The last column of ex contains expected output. How can I do that (at best with tidyverse)?
Edit
A solution using tidyverse would bes still much appreciated.