我需要使用dplyr(下面的代码)传递一个字符串作为列名.我无法让它工作.我试过使用[[名字]]和.数据[[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)

推荐答案

我会使用命名向量,而不是试图混淆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
# ...

编辑

在这种情况下,你可能会发现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")

R相关问答推荐

使用visnetwork重新创建层次 struct 树

将coord_sf与geom_spatraster一起使用会更改分辨率

返回句子中最长的偶数长单词

指定要保留在wrap_plots中的传奇

按块将载体转换为矩阵-reshape

在数据表中呈现数学符号

查找图下的面积

在发布到PowerBI Service时,是否可以使用R脚本作为PowerBI的数据源?

将年度数据插入月度数据

如何在geom_col中反转条

汇总数据表中两个特定列条目的值

Ggplot2中geom_tile的动态zoom

如何根据数据帧中的值从该数据帧中提取值?

识别连接的子网(R-igraph)

从R中的对数正态分布生成随机数的正确方法

为什么在BASE R中绘制线条时会看到线上的点?

R如何将列名转换为更好的年和月格式

通过初始的shiny 应用更新部署的shiny 应用的数据和参数,其中部署的应用程序显示为URL

带RStatix的Wilcoxon环内检验

SHILINY中DT列的条件着色