Use filter in dplyr conditional on an if statement in R

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

Leave a Comment