Introduction
Changing variable names can be an unavoidable component of preparing data for analysis. In this blog entry, we’ll show you how to change variable names in R.
Load Libraries and Access Dataset
Load the following libraries:
library(tidyverse)
library(dplyr)
library(tibble)
If you haven’t already installed these packages, try:
install.packages(c("dplyr", "tibble", "tidyverse"))
Now let’s access the mtcars dataset in R. Type:
mtcars
glimpse(mtcars)
Here’s a glimpse of the dataset:
You can see the variable names on the left.
Renaming Variables in R
Let’s say you want to rename mpg as MPG. Try:
data(mtcars)
cars = as_tibble(mtcars)
cars = dplyr::rename(cars, MPG = mpg)
glimpse(cars)
You can confirm that the variable name has changed:
What if you wanted to change each of the variables into upper case? You could try the following R code:
cars = rename_all(cars, toupper)
glimpse(cars)
And now confirm the change:
You could also convert an all-caps variable list to lower case by using:
cars = rename_all(cars, tolower)
glimpse(cars)
BridgeText can help you with all of your statistical analysis needs.