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
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)