You can use a somewhat simple function like this:
beforeafter <- function(lgl, before=1L, after=1L, default=FALSE) {
befores <- if (before > 0L) sapply(seq_len(before), function(i) c(tail(lgl, n=-i), rep(default, i))) else c()
afters <- if (after > 0L) sapply(seq_len(after), function(i) c(rep(default, i), head(lgl, n=-i))) else c()
apply(cbind(befores, lgl, afters), 1, any)
}
vec <- (1:10 == 5)
vec
# [1] FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE
beforeafter(vec)
# [1] FALSE FALSE FALSE TRUE TRUE TRUE FALSE FALSE FALSE FALSE
beforeafter(vec, before=2, after=0)
# [1] FALSE FALSE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE
As an example:
rownames_to_column(mtcars) %>%
select(rowname, cyl, gear) %>%
filter(cyl == 4L, gear == 3L)
# rowname cyl gear
# 1 Toyota Corona 4 3
rownames_to_column(mtcars) %>%
select(rowname, cyl, gear) %>%
filter(beforeafter(cyl == 4L & gear == 3L))
# rowname cyl gear
# 1 Toyota Corolla 4 4
# 2 Toyota Corona 4 3
# 3 Dodge Challenger 8 3
This works well if your data is a constant frequency and you want to remove all observations within some constant samples from a known problem. It does not work as well when you want "within some time" from variable-frequency data. For that, I think you'll need dist
iteratively on all "known bad" points.