Search code examples
rdplyrzoorollapply

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


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?


Solution

  • 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