How to filter rows that occur sequentially that fit multiple conditions using dplyr
If there are overlaps, this will print the overlapping rows only once (i.e. all unique rows in the set of all possibly-overlapping groups)
library(dplyr, warn.conflicts = FALSE)
df %>%
mutate(cond = (Close >= Open) & lead(Close >= Open) & lead(Close) <= High) %>%
slice(unique(c(outer(0:3, which(cond), '+'))))
#> Date Time Open High Low Close Up Down cond
#> 1 01/14/2022 08:20 4617.00 4625.50 4617.00 4622.00 3218 3197 TRUE
#> 2 01/14/2022 08:25 4622.00 4625.00 4620.50 4624.50 2246 2199 FALSE
#> 3 01/14/2022 08:30 4624.75 4625.00 4620.50 4623.75 2817 2564 FALSE
#> 4 01/14/2022 08:35 4623.75 4625.00 4616.75 4620.75 5079 5702 FALSE
#> 5 01/14/2022 09:00 4610.00 4614.00 4607.00 4613.25 5139 3302 TRUE
#> 6 01/14/2022 09:05 4613.25 4614.50 4609.50 4614.00 2908 3206 FALSE
#> 7 01/14/2022 09:10 4614.00 4619.75 4614.00 4617.50 3943 3767 TRUE
#> 8 01/14/2022 09:15 4617.75 4621.25 4616.50 4619.00 4140 3059 TRUE
#> 9 01/14/2022 09:20 4619.00 4623.00 4616.00 4619.75 4026 3899 FALSE
#> 10 01/14/2022 09:25 4619.75 4621.50 4616.25 4619.50 3068 2770 FALSE
#> 11 01/14/2022 09:30 4619.50 4622.50 4617.75 4619.25 6227 6792 FALSE
#> 12 01/14/2022 09:40 4618.25 4638.75 4615.25 4635.00 31057 28216 TRUE
#> 13 01/14/2022 09:45 4634.75 4640.50 4629.25 4635.50 17725 18406 FALSE
#> 14 01/14/2022 09:50 4635.75 4645.75 4633.50 4635.25 20980 20660 FALSE
#> 15 01/14/2022 09:55 4635.25 4644.25 4633.25 4643.50 16256 15670 FALSE
#> 16 01/14/2022 10:35 4638.00 4640.00 4631.50 4639.50 12024 12161 TRUE
#> 17 01/18/2022 09:00 4610.50 4612.25 4609.50 4611.50 1619 1552 TRUE
#> 18 01/18/2022 09:05 4611.50 4612.75 4609.75 4612.00 2010 1985 FALSE
#> 19 01/18/2022 09:10 4612.00 4612.50 4609.25 4611.50 1503 1763 FALSE
#> 20 01/18/2022 09:15 4611.75 4612.50 4608.00 4609.50 1772 2402 FALSE
Created on 2022-01-20 by the reprex package (v2.0.1)
This also works
df %>%
mutate(cond = (Close >= Open) & lead(Close >= Open) & lead(Close) <= High) %>%
filter(purrr::reduce(1:3, ~ .x | lag(.x), .init = cond))