In this post we will learn how to rename a column name in a dataframe with another name saved in a variable using dplyr. We will use dplyr’s rename() function in combination with special functions that are part of tidyverse’s tidy eval functionalities.
First, let us load tidyverse and check the installed dplyr’s version.
library(tidyverse) packageVersion("dplyr") [1] '1.1.2'
We will use the in-built iris dataset to change the column name using a variable name.
iris %>% head() Sepal.Length Sepal.Width Petal.Length Petal.Width Species 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3.0 1.4 0.2 setosa 3 4.7 3.2 1.3 0.2 setosa 4 4.6 3.1 1.5 0.2 setosa 5 5.0 3.6 1.4 0.2 setosa 6 5.4 3.9 1.7 0.4 setosa
In this example, we would like to change to current column name “Sepal.Length” to “sepal_length”. Let us say the new name we would like to change to is stored in a variable.
name_in_a_variable = "sepal_length"
If we try to use dplyr’s rename() function in the usual way, we will get the following. In stead of the value of the variable, we get a column with the of the variable.
iris %>% rename(name_in_a_variable = Sepal.Length ) %>% head() name_in_a_variable Sepal.Width Petal.Length Petal.Width Species 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3.0 1.4 0.2 setosa 3 4.7 3.2 1.3 0.2 setosa 4 4.6 3.1 1.5 0.2 setosa 5 5.0 3.6 1.4 0.2 setosa 6 5.4 3.9 1.7 0.4 setosa
Renaming a column with variable name using !! and := in tidyverse
To change the column name with a name in a variable, we need to use two special characters, !! in front of the variable name and := in stead of the equal operator.
iris % rename(!!name_in_a_variable := Sepal.Length ) %>% head() sepal_length Sepal.Width Petal.Length Petal.Width Species 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3.0 1.4 0.2 setosa 3 4.7 3.2 1.3 0.2 setosa 4 4.6 3.1 1.5 0.2 setosa 5 5.0 3.6 1.4 0.2 setosa 6 5.4 3.9 1.7 0.4 setosa