Use filter in dplyr conditional on an if statement in R

前端 未结 3 1977
青春惊慌失措
青春惊慌失措 2020-12-08 03:17

Let me share an example of what I\'m trying to do, since the title may not be as clear as I\'d like it to be. This doesn\'t have reproducible code, but i can add a reproduci

相关标签:
3条回答
  • 2020-12-08 03:42

    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.

    0 讨论(0)
  • 2020-12-08 03:54

    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)
    
    0 讨论(0)
  • 2020-12-08 03:59

    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
    
    0 讨论(0)
提交回复
热议问题