How to Rename a Variable in R

When importing datasets, variable names could often be non-intuitive or not easy to read. So, at times you may have to change the variable names. This guide will explain how to rename a variable in R.

Install the Required Library

Rename() function is part of the tidyverse package. The tidyverse package allows us to make tabular data manipulation easier by using key data transformation functions in a single package. Install the tidyverse library by running the following code:

install.packages("tidyverse")

Load the tidyverse library by running the following code:

library(tidayverse)

Variable Names

To check the variable names in the dataset, use the name() function. For this example, we will use the in-built dataset provided by R, known as the iris dataset. However, you can use your own dataset. Run the following code:

name(iris)
Names Function
Name() function to check the variable names in the dataset.

Renaming Variable

To rename the variable, use the rename() function. The syntax of the rename function is:

rename(dataframe, new_name = old_name)

Arguments:

  • dataframe = Name of the dataset.
  • new_name = The name you want to give the variable.
  • old_name = The variable name you want to change.

For example, if we want to change the variable name “Species” to “Kind”, run the following code:

rename(iris,Kind=Species)
Rename Function Output
Rename Function to rename the variable in the dataset.

Was this article helpful?

Leave a Comment