15.5 Renaming Columns in a Data Frame

15.5.1 Problem

You want to rename the columns in a data frame.

15.5.2 Solution

Use rename() from dplyr. This returns a new data frame:

ToothGrowth %>%
  rename(length = len)

15.5.3 Discussion

You can rename multiple columns within the same call to rename():

ToothGrowth %>%
  rename(
    length = len,
    supplement_type = supp
  )
#>    length supplement_type dose
#> 1     4.2              VC  0.5
#> 2    11.5              VC  0.5
#>  ...<56 more rows>...
#> 59   29.4              OJ  2.0
#> 60   23.0              OJ  2.0

Renaming a column using base R is a bit more verbose. It uses the names() function on the left side of the <- operator.

# Make a copy of ToothGrowth for this example
ToothGrowth2 <- ToothGrowth

names(ToothGrowth2)  # Print the names of the columns
#> [1] "len"  "supp" "dose"

# Rename "len" to "length"
names(ToothGrowth2)[names(ToothGrowth2) == "len"] <- "length"

names(ToothGrowth)
#> [1] "len"  "supp" "dose"

15.5.4 See Also

See ?select for more ways to rename columns within a data frame.