Avoiding error when using rename in dplyr and column doesn't exist

前端 未结 7 1979
暖寄归人
暖寄归人 2021-02-07 03:15

Is there a clever way to use the rename function in dplyr when in some instances the column to be renamed doesn\'t exist?

For example, I would like the following not to

7条回答
  •  无人及你
    2021-02-07 03:27

    One more solution that can safely operate within dplyr without throwing an error using conditional evaluation {}. This will apply the rename if "foo" exists, but continue execution with the original df in the absence of a column named "foo".

    mtcars %>%
    {if("foo" %in% names(.)) rename(., missing_varible=foo) else .} %>%
    rename(miles_per_gallon=mpg) 
    

提交回复
热议问题