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

前端 未结 7 1971
暖寄归人
暖寄归人 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)
    
    0 讨论(0)
提交回复
热议问题