In this tutorial, we will learn how to rename column name of a dataframe in R using dplyr’s rename() function. We will first see the basic syntax to use to change the name of a column with dplyr’s rename(). Then we will see an example of of changing one column name and next wee will rename two column names using rename() function.
With dplyr’s rename(). function we can rename one or more columns’ names using the following syntax.
dplyr::rename(dataframe, new_name = old_name)
where old_name is current column name in the dataframe and new_name is new name of the column after using rename() function. Note we don’t specify the names within quotes.
library(tidyverse)
Let us use the buint-in iris dataset to see examples of renaming column names with dplyr’s rename() function.
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
How to rename a column with dplyr’s rename()
The column names of the original iris dataset is in Camel Case with two words separted by a dot “.”. Let us clean up the column name and use dplyr’s rename() function to change to new name.
In the example below, we are changing the column name “Sepal.Length” to “sepal_length”.
iris %>% rename(sepal_length = Sepal.Length)
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
How to rename multiple columns in R with dplyr’s rename()
With dplyr’s rename() function, we can also rename multiple column names at the same time. Here, in addition to the first column’s name we are also changing the second column’s name using dplyr’s rename()
iris %>% rename(sepal_length = Sepal.Length, sepal_width = Sepal.Width)
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
You might also want to learn how to rename columns by adding a prefix or suffix to all column names or select column names.
Check out the post to use dplyr’s rename_with() function to add Prefix/Suffix to Column Names of a dataframe in R