Jazzmatazz
Jazzmatazz

Reputation: 645

Rename all column names with a suffix except listed column name using dplyr?

I'm hoping this is a simple question. How do I rename all of the column header names in a data set with the suffix "_2017" except the first 2 column headers which are: "Name", and "State"? I'd like to use dplyr to do this.

Upvotes: 9

Views: 9245

Answers (2)

HBat
HBat

Reputation: 5692

rename_if(), rename_at(), and rename_all() have been superseded by 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

Upvotes: 10

akuiper
akuiper

Reputation: 214957

You can use rename_at and exclude columns using vars helper method:

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

Exclude with hard coded names:

df %>% rename_at(vars(-Name, -State), ~ paste0(., '_2017'))
#  Name State col1_2017 col2_2017
#1    a     c         1         3
#2    b     d         2         4

Exclude by column positions:

df %>% rename_at(vars(-(1:2)), ~ paste0(., '_2017'))
#  Name State col1_2017 col2_2017
#1    a     c         1         3
#2    b     d         2         4

Exclude by column names stored in a variable:

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

Upvotes: 15

Related Questions