(与之有关的问题:在dplyr的rename函数中输入新的列名)
在 dplyr
链式操作(%>%
) 中,我希望能够用旧列名的函数(如 tolower
或 gsub
等)来替换多个列名。
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
作为一个以旧名称为名、新名称为值的命名字符向量的参数。
于是我尝试了:
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 ....
iris %>% \
names<-`(.,tolower( gsub("\.", "_", names(.) ) ))`(我只是开玩笑而已)。 - Frankrename_with
是最新的dplyr动词,可使用函数对变量进行编程重命名。请参见下面的答案。 - Paul Rougieux