(Somewhat related question: Enter new column names as string in dplyr's rename function)

dplyr链(%>%)的中间,我想用其旧名称(使用tolowergsub等)替换多个列名.

library(tidyr); library(dplyr)
data(iris)
# This is what I want to do, but I'd like to use dplyr syntax
names(iris) <- tolower( gsub("\\.", "_", names(iris) ) )
glimpse(iris, 60)
# Observations: 150
# Variables:
#   $ sepal_length (dbl) 5.1, 4.9, 4.7, 4.6, 5.0, 5.4, 4.6,...
#   $ sepal_width  (dbl) 3.5, 3.0, 3.2, 3.1, 3.6, 3.9, 3.4,...
#   $ petal_length (dbl) 1.4, 1.4, 1.3, 1.5, 1.4, 1.7, 1.4,...
#   $ petal_width  (dbl) 0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.3,...
#   $ species      (fctr) setosa, setosa, setosa, setosa, s...

# the rest of the chain:
iris %>% gather(measurement, value, -species) %>%
  group_by(species,measurement) %>%
  summarise(avg_value = mean(value)) 

我看?rename把论点replace当作named character vector, with new names as values, and old names as names.

所以我试着:

iris %>% rename(replace=c(names(iris)=tolower( gsub("\\.", "_", names(iris) ) )  ))

但这(a)返回Error: unexpected '=' in iris %>% ...,并且(b)需要按名称引用链中上一个操作中的数据帧,而在我的实际用例中,我不能这样做.

iris %>% 
  rename(replace=c(    )) %>% # ideally the fix would go here
  gather(measurement, value, -species) %>%
  group_by(species,measurement) %>%
  summarise(avg_value = mean(value)) # I realize I could mutate down here 
                                     #  instead, once the column names turn into values, 
                                     #  but that's not the point
# ---- Desired output looks like: -------
# Source: local data frame [12 x 3]
# Groups: species
# 
#       species  measurement avg_value
# 1      setosa sepal_length     5.006
# 2      setosa  sepal_width     3.428
# 3      setosa petal_length     1.462
# 4      setosa  petal_width     0.246
# 5  versicolor sepal_length     5.936
# 6  versicolor  sepal_width     2.770
# ... etc ....  

推荐答案

我想你看的是plyr::rename份文件,而不是dplyr::rename份.你可以用dplyr::rename做这样的事情:

iris %>% rename_(.dots=setNames(names(.), tolower(gsub("\\.", "_", names(.)))))

R相关问答推荐

使用每个组的最后一行连接两个数据帧

使用ggcorrplot删除值,但保留不重要相关性的 colored颜色

在' geom_contour_filled()'中对齐两个gplot的 colored颜色 比例

如何替换某个字符的所有出现,但如果该字符是字符串中的第一个,则不替换?

将虚线添加到每个站点的传奇中平均

R:对于没有数据的缓冲区,加权平均值为0

即使声明引发错误,R函数也会在第二次try 时返回结果

IQR()和stats之间四分位距计算的差异::分位数()在R和' ggpubr '

在R中使用自定义函数时如何删除该函数的一部分?

根据R中两个变量的两个条件删除带有dspirr的行

在R中按行按列范围查找最大值的名称

如何在PackageStatus()中列出&q;不可用的包&q;?

将多个列值转换为二进制

在R中创建连续的期间

从多面条形图中删除可变部分

按组计算列中1出现的间隔年数

在具有多个响应变量的比例堆叠条形图上方添加总计

循环遍历多个变量,并将每个变量插入函数R

Conditional documentr::R中数据帧的summarize()

如何显示准确的p值而不是<;0.001*?