How to flag the values of a column based on values of another column in R by using rollapply?

Solution 1:

Using rollapply -

library(dplyr)
library(zoo)

df %>%
  mutate(flag = rollapply(L > 6, 3, any, fill = FALSE))

#    T  L  flag
#1   1  1 FALSE
#2   2  2  TRUE
#3   3  9  TRUE
#4   4  4  TRUE
#5   5  6  TRUE
#6   6  8  TRUE
#7   7  3  TRUE
#8   8  4 FALSE
#9   9  2 FALSE
#10 10  5 FALSE
#11 11  2 FALSE
#12 12  5  TRUE
#13 13  9  TRUE
#14 14 10  TRUE
#15 15  3  TRUE
#16 16  5 FALSE
#17 17  1 FALSE
#18 18  1 FALSE
#19 19  2 FALSE
#20 20  2 FALSE

Solution 2:

I guess we can do it without rollapply. Perhaps we can try the code below

transform(
  df,
  Flag = seq_along(L) %in% pmax(pmin(sort(unique(outer(-1:1, which(L > 6), `+`))), length(L)), 1)
)

which gives

    T  L  Flag
1   1  1 FALSE
2   2  2  TRUE
3   3  9  TRUE
4   4  4  TRUE
5   5  6  TRUE
6   6  8  TRUE
7   7  3  TRUE
8   8  4 FALSE
9   9  2 FALSE
10 10  5 FALSE
11 11  2 FALSE
12 12  5  TRUE
13 13  9  TRUE
14 14 10  TRUE
15 15  3  TRUE
16 16  5 FALSE
17 17  1 FALSE
18 18  1 FALSE
19 19  2 FALSE
20 20  2 FALSE