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.
rename() function from dplyr takes a syntax rename(new_column_name = old_column_name) to change the column from old to a new name. The following example renames the column from id to c1 . The operator – %>% is used to load the renamed column names to the data frame.
To remove all columns with a common suffix from an R data frame, you need to use the grep() function. This function identifies and returns a vector with all columns that share the suffix. You can use this vector as an argument of the select() function to remove the columns from the data frame.
Rename All Column Names Using colnames() colnames() is the method available in R which can be used to rename all column names (list with column names). Actually, colnames() is used to set or get the names of a dataframe. You can also use this method to rename dataframe column by index in R.
To change multiple column names by name and by index use rename() function of the dplyr package and to rename by just name use setnames() from data. table . From R base functionality, we have colnames() and names() functions that can be used to rename a data frame column by a single index or name.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With