We wish to specify the function to be applied to the current column names to generate the desired names.
In this section, we cover the following function specification scenarios:
lambda
function to each column name. Passing an anonymous (lambda
) function which works similarly to a function but is often more convenient especially when parameters need to be passed.The examples we show here rename all columns of a data frame. See Column Selection for Implicit Renaming for how to apply the renaming function to a selected set of columns only.
We wish to rename columns by applying a named function to the current column names to generate the desired column names.
Built-In Function
In this example, we wish to convert the upper-case column names to lower-case.
df_2 = df %>% rename_with(str_to_lower)
Here is how this works:
rename_with()
from the dplyr
package to apply a function to the current column names to generate the desired column names.rename_with()
the name of the function that we wish to apply to each column name, which here is str_to_lower()
.Custom Function
In this example, we wish to have column names follow the template 'col_{col}_v2'
where {col}
is the current column name.
format_name <- function(p_col) {
str_glue('col_{p_col}_v2')
}
df_2 = df %>% rename_with(format_name)
Here is how this works:
rename_with
our custom function format_name()
.str_glue()
to insert each current column name in the desired naming template. See String Interpolation.We wish to rename columns by applying a lambda
function to the current column names to generate the desired column names.
df_2 = df %>%
rename_with(~ str_trim(.) %>%
str_to_lower() %>%
str_replace_all(' ', '_'))
Here is how this works:
rename_with()
an anonymous function (i.e. a one-sided formula).In this example, the anonymous function takes a column name and applies a set of string manipulation operations.
str_trim()
str_to_lower()
str_replace_all()
See String Operations.
In this solution, the renaming logic is applied to all columns. See Column Selection for Implicit Renaming for how to apply the renaming function to a selected set of columns only.