我有一个数据框,可以过滤,删除和添加一些列,然后我想使用管道(%>%
)重命名所有列。
但是,我不明白如何获取当前的colnames向量(在%>%
内)并将其替换为另一个向量?如果我不删除列,这似乎很简单,但是如何在管道链中“更新” colnames
的向量?
library(dplyr)
library(tidyr)
data("mtcars")
mtcars %>%
filter(disp < 200) %>%
dplyr::select(-c('mpg','cyl', "disp")) %>%
mutate(Type = 2) %>%
# rename_at(vars(names(df), # how to rename the columns???
# function(x) paste(names(df), "new", sep = "_"))) %>%
head(2)
我得到的是
hp drat wt qsec vs am gear carb Type
1 110 3.9 2.620 16.46 0 1 4 4 2
2 110 3.9 2.875 17.02 0 1 4 4 2
我期望的(更改的姓氏)
hp_new drat_new wt_new qsec_new vs_new am_new gear_new carb_new Type_new
1 110 3.9 2.620 16.46 0 1 4 4 2
2 110 3.9 2.875 17.02 0 1 4 4 2
答案 0 :(得分:6)
我们可以使用rename_all
library(dplyr)
mtcars %>%
filter(disp < 200) %>%
dplyr::select(-c('mpg','cyl', "disp")) %>%
mutate(Type = 2) %>%
rename_all(~paste0(., "_new")) %>% head
# hp_new drat_new wt_new qsec_new vs_new am_new gear_new carb_new Type_new
#1 110 3.90 2.620 16.46 0 1 4 4 2
#2 110 3.90 2.875 17.02 0 1 4 4 2
#3 93 3.85 2.320 18.61 1 1 4 1 2
#4 62 3.69 3.190 20.00 1 0 4 2 2
#5 95 3.92 3.150 22.90 1 0 4 2 2
#6 123 3.92 3.440 18.30 1 0 4 4 2
答案 1 :(得分:2)
我们可以将rename_all
与str_c
(tidyverse方法)一起使用
library(dplyr)
library(stringr)
mtcars %>%
filter(disp < 200) %>%
dplyr::select(-c('mpg','cyl', "disp")) %>%
mutate(Type = 2) %>%
rename_all(~ str_c(., "_new")) %>%
head(2)
# hp_new drat_new wt_new qsec_new vs_new am_new gear_new carb_new Type_new
#1 110 3.9 2.620 16.46 0 1 4 4 2
#2 110 3.9 2.875 17.02 0 1 4 4 2
或者另一个选择是set_names
mtcars %>%
filter(disp < 200) %>%
dplyr::select(-c('mpg','cyl', "disp")) %>%
mutate(Type = 2) %>%
set_names(str_c(names(.), "_new"))
或使用base R
nm1 <- setdiff(names(mtcars), c("mpg", "cyl", "disp"))
setNames(subset(mtcars, disp < 200, select = nm1), paste0(nm1, "_new"))