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

前端 未结 7 1967
暖寄归人
暖寄归人 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:37

    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)
    

提交回复
热议问题