We wish to rename columns of a data frame by providing a mapping from the current column names to the desired names for the columns whose names we wish to change. This is the recommended approach to column renaming (when it is possible).
In this example, we wish to change the names of two columns from col_a
and col_b
to col_1
and col_2
respectively.
df_2 = df %>%
rename(col_1 = col_a, col_2 = col_b)
Here is how this works:
rename()
from dplyr
to change column names from their current values to the desired values.rename()
expects a mapping between the current column names and the desired column names of the form desired_name = current_name
which in this case is col_1 = col_a, col_2 = col_b
.rename()
will retain their current names.Alternative: Rename while Selecting
df_2 = df %>%
select(col_1 = col_a, col_2 = col_b)
Here is how this works:
tidyverse
is the select()
function. See Selecting.select()
, we can rename them to the desired names by passing a mapping between the current column names and the desired column names of the form desired_name = current_name
which in this case is col_1 = col_a, col_2 = col_b
.