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

后端 未结 2 1384
孤城傲影
孤城傲影 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:13

    I think this is what you were looking for. It is the use of rename_ as @Henrik suggested, but the argument has an, lets say, interesting, name:

    > myFunc <- function(df, col){
    +   new <- paste0(col, '_1')
    +   out <- dplyr::rename_(df, .dots=setNames(list(col), new))
    +   return(out)
    + }
    > myFunc(data.frame(x=c(1,2,3)), "x")
      x_1
    1   1
    2   2
    3   3
    >
    

    Note the use of setNames to use the value of new as name in the list.

    0 讨论(0)
  • 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]})
    
    0 讨论(0)
提交回复
热议问题