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

前端 未结 7 2093
暖寄归人
暖寄归人 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条回答
  •  旧时难觅i
    2021-02-07 03:37

    You can use rename_at() to accomplish this:

    mtcars %>%
      rename_at(vars(matches("^missing_var$")), function(x) "foo")
    

    Doesn't return an error if "missing_var" isn't in your data.frame. If you want to replace multiple variables that may or may not exist, you can put the original and new names in a named vector/list, write a short little function to return the new variable name.

    customRename <- function(orig_name) {
      renames <- c(
        foo = "OOF",
        bar = "RAB",
        fi = "IF")
      renames[[orig_name]]
    }
    
    mtcar %>%
      rename_at(vars(matches("^foo$|^bar$|^fi$")), customRename)
    

提交回复
热议问题