使用dplyr将除指定列名外的所有列名添加后缀。

8

我希望这是一个简单的问题。如何在数据集中重命名所有列头名称,并加上后缀 "_2017",除了前两个列头:"Name"和"State"?我想使用 dplyr 来实现。

2个回答

14

您可以使用rename_atvars帮助方法来排除列:

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

9

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接