Execute dplyr operation only if column exists

前端 未结 6 1834
青春惊慌失措
青春惊慌失措 2021-02-07 09:18

Drawing on the discussion on conditional dplyr evaluation I would like conditionally execute a step in pipeline depending on whether the reference column exists in the passed da

6条回答
  •  猫巷女王i
    2021-02-07 09:59

    I know I'm late to the party, but here's an answer somewhat more in line with what you were originally thinking:

    mtcars %>%
      filter(am == 1) %>%
      {
        if("cyl" %in% names(.)) filter(., cyl == 4) else .
      }
    

    Basically, you were missing the . in filter. Note this is because the pipeline doesn't add . to filter(expr) since it is in an expression surrounded by {}.

提交回复
热议问题