Home > Software design >  Using dplyr to select next row based on condition in R
Using dplyr to select next row based on condition in R

Time:09-09

I want to select the lead() row based on the a condition (var1 >= 5): Example data:

df1 <- data.frame(ID = c(1, 2, 3, 4, 5),
                  var1 = c(10, 1, 10, 4, 1),
                  var2 = c('a', 'b', 'c', 'd', 'e'))

So the resulting dataframe would look like this:

ID    var1    var2 
2       1        b
4       4        d

I have tried this, but know that case_when is not the correct operator for this task:

df1%>% 
  case_when(var1>= 5 ~ select_(lead(var2)))

Does anyone know a quick and easy way to do this using dplyr? Thanks!

CodePudding user response:

Based on your expected output what you're looking for is answered by:

df1 |> filter(lag(var1) >= 5)

  ID var1 var2
1  2    1    b
2  4    4    d

In other words, get the following row after var1 >= 5?

  • Related