rdataframeif-statementrollapply

Roll condition ifelse in R data frame


I have a data frame with two columns in R and I want to create a third column that will roll by 2 in both columns and check if a condition is satisfied or not as described in the table below. The condition is a rolling ifelse and goes like this :

IF -A1<B3<A1 TRUE ELSE FALSE

IF -A2<B4<A2 TRUE ELSE FALSE

IF -A3<B5<A3 TRUE ELSE FALSE

IF -A4<B6<A4 TRUE ELSE FALSE

A B CHECK
1 4 NA
2 5 NA
3 6 FALSE
4 1 TRUE
5 -4 FALSE
6 1 TRUE

How can I do it in R? Is there a base R's function or within the dplyr framework ?


Solution

  • Since R is vectorized, you can do that with one command, using for instance dplyr::lag:

    library(dplyr)
    df %>% 
      mutate(CHECK = -lag(A, n=2) < B & lag(A, n=2) > B)
    
      A  B CHECK
    1 1  4    NA
    2 2  5    NA
    3 3  6 FALSE
    4 4  1  TRUE
    5 5 -4 FALSE
    6 6  1  TRUE