Search code examples
rselectfilterconditional-statements

How to select the row with specific condition and the row just above?


Here is how I defined my condition , but I need the row just above as well. There are many observations per ID.

data2<- data2 %>% 
  group_by (ID_number)  %>%  
  filter(time_diff_hour > 8.000 | is.na(time_diff_hour))

Solution

  • You can add filter conditions with the lead function, which will return a row above the tested row. In opposite, if you need to return a row below the tested row, you can use the lag function.

    data2<- data2 %>% 
      group_by (ID_number)  %>%  
      filter(time_diff_hour > 8.000 | is.na(time_diff_hour) | 
             lead(time_diff_hour) > 8.000 | is.na(lead(time_diff_hour)))