What is the dplyr rename() function in R?

Overview

In the dplyr package, we use the rename() function to rename each variable or column name individually. It changes the column names, but the column order is preserved along with DataFrame attributes.

Syntax


rename(.data, ...)

Parameters

It takes the following argument values.

  • .data: This can be a DataFrame, a tibble, or a lazy DataFrame.
  • ...: This is an additional argument, used to rename variables names as new_name=old_name.

Return value

It returns an updated object of the same type as .data.

Example

In this code snippet, we'll discuss the rename() function from the dplyr package to rename the column names of the iris dataset.

library("dplyr")
# Load iris dataset as R tibble
iris <- as_tibble(iris)
# Print loaded dataset
print(iris)
# update new_name = old_name
# as petal_length = Petal.Length
rename(iris, petal_length = Petal.Length)

Explanation

  • Line 3: The as_tibble(iris) keyword will load the iris dataset as an R tibble in the iris variable.
  • Line 5: We print the loaded dataset on the console to show rows and columns.
  • Line 8: We invoke rename(iris, petal_length = Petal.Length) which will change the current variable name Petal.Length to Petal_Length.

Free Resources