Execute dplyr operation only if column exists

前端 未结 6 1827
青春惊慌失措
青春惊慌失措 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条回答
  •  青春惊慌失措
    2021-02-07 09:51

    This code does the trick and is pretty flexible. The ^ and $ are regex used to perform an exact match.

    mtcars %>% 
      set_names(names(.) %>% 
                  str_replace("am","1") %>% 
                  str_replace("^cyl$","2") %>% 
                  str_replace("Doesn't Exist","3")
                  )
    

提交回复
热议问题