将字符串解析为 dplyr 中的列名

lec*_*ecb 2 r dplyr

我需要使用 dplyr (下面的代码)传递一个字符串作为列名。我无法让它工作。我尝试过使用 [[name]] 和 .data[[name]] 但这不起作用。我特别需要一个解决方案,允许我将列重命名为我在变量中指定的字符串name

colnames(mtcars) -> cols

rename_cols <- function(col) {
  
  name = paste0(col, "_new") #I want to be able to parse this into the rename function below

  mtcars %>% 
    rename(
      name = col,
    )
}

lapply(cols, rename_cols)
Run Code Online (Sandbox Code Playgroud)

小智 5

我会使用命名向量,而不是试图搞乱 dplyr 编程的细微差别。一个好处是该方法已经矢量化。

rename_cols <- function(col) {
  
  name = paste0(col, "_new") #I want to be able to parse this into the rename function below
  
  mtcars %>% 
    rename(setNames(col, name))
}

rename_cols(colnames(mtcars))
#                     mpg_new cyl_new disp_new hp_new drat_new wt_new qsec_new vs_new am_new gear_new carb_new
# Mazda RX4              21.0       6    160.0    110     3.90  2.620    16.46      0      1        4        4
# Mazda RX4 Wag          21.0       6    160.0    110     3.90  2.875    17.02      0      1        4        4
# Datsun 710             22.8       4    108.0     93     3.85  2.320    18.61      1      1        4        1
# Hornet 4 Drive         21.4       6    258.0    110     3.08  3.215    19.44      1      0        3        1
# Hornet Sportabout      18.7       8    360.0    175     3.15  3.440    17.02      0      0        3        2
# Valiant                18.1       6    225.0    105     2.76  3.460    20.22      1      0        3        1
# ...
Run Code Online (Sandbox Code Playgroud)

编辑

在这种情况下,您可能还会发现rename_with()这正是您所需要的。

library(dplyr)

colnames(mtcars) -> cols

mtcars %>% 
  rename_with(~ paste0(., "_new"), any_of(cols))

# which is the same as the more concise but maybe less clear...
mtcars %>% 
  rename_with(paste0, any_of(cols), "_new")
Run Code Online (Sandbox Code Playgroud)