When cleaning data you’ll almost always need to rename the columns in R. And if you’re like me, you’ll forget how to do it every time. I wanted to create this post as a reference for how to rename the columns. I’ll be going over two ways to rename the columns. One method uses base R. This one is my favorite. The other uses the Tidyverse.
Renaming Columns using base R
# Rename column where names is "OldName" to "NewName" names(data)[names(data) == "OldName"] <- "NewName" names(data)[names(data) == "OtherOldName"] <- "OtherNewName"
Explaining the code. you’ll use the “name” function to bring up a vector of the column names. Use the dataset name within the “name()” function in this code example data is the data set. Using the bracket notation with the “names(data)” you select the specific column name. Then use “<-” to assign it a new value. It’s very straight forward once you understand how the bracket notation works.
I enjoy using the base R method because you can use R’s bracket notation which I find very intuitive and powerful.
Renaming Columns Using The Tidyverse
# Rename column where names is "OldName" to "NewName" data %>% rename( NewName = OldName, OtherNewName = OtherOldName )
The Code. Like with most dplyr(This is a part of the Tidyverse) chains start with your dataframe. In this example the dataframe is data. Then add the chain “%>%” to lead to the “rename()” function. Within the “rename()” function it’s very simple. Have the “NewName” equal the “OldName” and the names will be replaced.
It is slightly counter-intuitive that the new name comes before the old name. That’s really the only thing to be on the look for in this code. You’ll know pretty quick too if you have the order wrong.
The Tidyverse is such a powerful R package. I use it frequently. the ability to chain functions is a game changer and I highly recommend everyone use the Tidyverse and get comfortable with it.
So those are my two favorite methods for how to rename columns in R. To see more about the TIdyverse and R you can look at my DataViz project from Reddit. The post also shows how some interesting ggplot2 graphs.