我希望这是一个简单的问题。如何使用后缀" _2017"重命名数据集中的所有列标题名称?除前两个列标题是:"名称"和"状态"?我想用dplyr来做这件事。
答案 0 :(得分:3)
您可以使用rename_at
并使用vars
辅助方法排除列:
df <- data.frame(Name = c('a', 'b'), State = c('c', 'd'), col1 = 1:2, col2 = 3:4)
df
# Name State col1 col2
#1 a c 1 3
#2 b d 2 4
使用硬编码名称排除:
df %>% rename_at(vars(-Name, -State), ~ paste0(., '_2017'))
# Name State col1_2017 col2_2017
#1 a c 1 3
#2 b d 2 4
按列位置排除:
df %>% rename_at(vars(-(1:2)), ~ paste0(., '_2017'))
# Name State col1_2017 col2_2017
#1 a c 1 3
#2 b d 2 4
按存储在变量中的列名排除:
to_exclude = c('Name', 'State')
df %>% rename_at(vars(-one_of(to_exclude)), ~ paste0(., '_2017'))
# Name State col1_2017 col2_2017
#1 a c 1 3
#2 b d 2 4
答案 1 :(得分:0)
rename_if()
, rename_at()
和rename_all()
已被rename_with()
取代。
df <- data.frame(Name = c('a', 'b'), State = c('c', 'd'),
col1 = 1:2, col2 = 3:4)
# De-select by location
df %>% rename_with(~paste0(., "_2017"), -c(1:2))
#> Name State col1_2017 col2_2017
#> 1 a c 1 3
#> 2 b d 2 4
# De-select by name
df %>% rename_with(~paste0(., "_2017"), -c("Name", "State"))
#> Name State col1_2017 col2_2017
#> 1 a c 1 3
#> 2 b d 2 4
# De-select using another variable that holds names
deselect_names <- c("Name", "State")
df %>% rename_with(~paste0(., "_2017"), -!!deselect_names)
#> Name State col1_2017 col2_2017
#> 1 a c 1 3
#> 2 b d 2 4