Enter new column names as string in dplyr's rename function

后端 未结 2 1386
孤城傲影
孤城傲影 2020-12-05 13:30

dplyr\'s rename functions require the new column name to be passed in as unquoted variable names. However I have a function where the column name is constructed by pasting a

2条回答
  •  我在风中等你
    2020-12-05 14:15

    Recent updates to tidyr and dplyr allow you to use the rename_with function.

    Say you have a data frame:

    library(tidyverse)
    
    df <- tibble(V0 = runif(10), V1 = runif(10), V2 = runif(10), key=letters[1:10])
    

    And you want to change all of the "V" columns. Usually, my reference for columns like this comes from a json file, which in R is a labeled list. e.g.,

    colmapping <- c("newcol1", "newcol2", "newcol3")
    names(colmapping) <- paste0("V",0:2)
    

    You can then use the following to change the names of df to the strings in the colmapping list:

    df <- rename_with(.data = df, .cols = starts_with("V"), .fn = function(x){colmapping[x]})
    

提交回复
热议问题