How to Rename Variables in R
I want to show you how to rename variables in R. This is a basic task but one that I do frequently when working with a new dataset. Renaming variables is useful, especially when creating graphics. For example, if I were plotting these data, I would want the variable name to show as “Coffee Roast” rather than “coffee.” If I were just doing data wrangling, I wouldn’t care as much about the variable name. But when presenting data, I want the text to be grammatically correct and specific. I will show you how to do this using dplyr::rename and then using base R.
When I first started learning R, I remember being frustrated there wasn’t a clear example of how to do this. Now there is!
You might interested in my other post How to Recode Factor and Character Variables in R.
# First, let's create a new data set in R, # called “gimmeCaffeine.” It has 2 variables (coffee and origin). # We will use dplyr::tribble to input the data. tribble creates an # easy to read dataset. library(dplyr) gimmeCaffeine <- tribble( ~coffee, ~origin, "light", "colombia", "medium", "ethiopia", "dark", "peru") # Using dplyr::rename to change the variable name. A "variable" is also commonly # referred to as a column name. Since we have a space between Coffee Roast, # we need to use parentheses. If we instead used coffeeRoast, the parentheses # wouldn't be needed. # Using dplyr::rename gimmeCaffeine <- rename(gimmeCaffeine, "Coffee Roast" = coffee) # Using base R colnames(gimmeCaffeine)[colnames(gimmeCaffeine) == "coffee"] <- "Coffee Roast" It's as easy as that!