15.5 Renaming 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
ToothGrowth
ToothGrowth2 <-
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"