Use filter in dplyr conditional on an if statement in R

Building on lukeA's comment, you could also use case_when():

library(dplyr)
y <- ""
data.frame(x = 1:5) %>% 
  filter(case_when(y=="" ~ x > 3, #When y == "", x > 3
                   T ~ x<3) #Otherwise, x < 3
         ) %>% 
  tail(1)

This would be better particularly if you have more than two conditions to evaluate.


You could do

library(dplyr)
y <- ""
data.frame(x = 1:5) %>% 
  {if (y=="") filter(., x>3) else filter(., x<3)} %>% 
  tail(1)

or

data.frame(x = 1:5) %>% 
 filter(if (y=="") x>3 else x<3) %>%  
  tail(1)

or even store your pipe in the veins of

mypipe <- . %>% tail(1) %>% print
data.frame(x = 1:5) %>% mypipe

See if the below code works, where we insert the if-else condition in the filter statement. This makes sense because the latter statements accepts a logical statement as its input -- we just use the former statement to control the value of the input.

library(dplyr)

newdf <- mydf %>%    
  filter(
    if (this_team != "") {
      team == this_team
    } else {
      firstname == this_name & lastname == that_name
    }
  ) %>%
  mutate(totalrows = nrow(.)) %>%
  group_by(x1, y1) %>%
  summarize(dosomestuff)

Tags:

R

Dplyr