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

后端 未结 2 1385
孤城傲影
孤城傲影 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.

提交回复
热议问题