I want to show you how to rename variables and character strings in R. This is a basic task but one that I do frequently when working with a new dataset. Renaming variables and character strings 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. Let’s get started!
# 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 library(dplyr) gimmeCaffeine <- tribble( ~coffee, ~origin, "light", "colombia", "medium", "ethiopia", "dark", "peru") # To have a more specific variable name, let's change # "coffee" to "Coffee Roast". This is base R code and doesn't # call dplyr. colnames(gimmeCaffeine)[colnames(gimmeCaffeine) == "coffee"] <- "Coffee Roast" # Let's change the character strings within the # "origin" variable. This is base R code and doesn't call dplyr. gimmeCaffeine$origin[gimmeCaffeine$origin == "peru"] <- "Peruvian"
It’s as easy as that!