We wish to add a prefix or a suffix to the names of columns of a data frame.
In this section, we add a prefix or a suffix to the names of all columns. To only modify the names of specific columns, see Column Selection for Implicit Renaming.
We wish to add a prefix (a substring that comes before the current column name) to the names of columns of a data frame.
In this example, we wish to add the prefix ‘B_’
to the names of all columns.
df_2 = df %>%
rename_with(~ str_c('B', .x, sep = "_"))
Here is how this works:
rename_with()
to rename columns by applying a function to existing column names and using the output as the new column names. See Implicit Renaming.rename_with()
an anonymous function (a one-sided formula) that takes the current column names and uses the function str_c()
to concatenate to them the prefix ‘B’
separated by an underscore (as specified by the sep
argument of str_c()
). See String Combining.We wish to add a suffix (a substring that comes after the current column name) to the names of columns of a data frame.
In this example, we wish to add the suffix ‘_B’
to the names of all columns.
df_2 = df %>%
rename_with(~ str_c(.x, 'B', sep = "_"))
Here is how this works:
rename_with()
to rename columns by applying a function to existing column names and using the output as the new column names. See Implicit Renaming.rename_with()
an anonymous function (a one-sided formula) that takes the current column names and uses the function str_c()
to concatenate to them the suffix ‘B’
separated by an underscore (as specified by the sep
argument of str_c()
). See String Combining.