2

I have a data frame, like this:

df <- data.frame (T  = c(1:20), L = c(1,2,9,4,6,8,3,4,2,5,2,5,9,10,3,5,1,1,2,2))

I want to Flag a T value Ti (and also Ti−1 and Ti+1) if Li is bigger than 6 (i.e. 3 values in total are flagged then).

How to do it by Rollapply?

Anoushiravan R
  • 21,622
  • 3
  • 18
  • 41

2 Answers2

2

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
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thank you for your response, I would appreciate it if you could kindly tell me what does "any" stand for? – Faranak omidi Jan 13 '22 at 09:00
  • `any` returns `TRUE` if any of the values has `TRUE` value in it. Maybe running these lines would help clarify the difference `any(TRUE, FALSE, FALSE)`, ` any(FALSE, FALSE, FALSE)` and `any(TRUE, FALSE, TRUE)`. – Ronak Shah Jan 13 '22 at 10:29
1

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
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81