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
First, define a list with your column names you want to rename in a data frame df.
columnNamesToRename <-
list(
newColumnName1 = "oldColumnName1",
newColumnName2 = "oldColumnName2"
)
Next, remove the elements of the list, which have a column name as their name, but is not a column name of your data frame:
columnNamesToRename.WhichAreColumnNamesInTibble <-
columnNamesToRename[columnNamesToRename %in% intersect(
unlist(columnNamesToRename),
colnames(df)
)]
Then, you can rename the column names using the named list columnNamesToRename.WhichAreColumnNamesInTibble:
df.WithRenamedColumnNames <-
df %>% dplyr::rename(!!!columnNamesToRename.WhichAreColumnNamesInTibble)