Change Column Name of Data Frame in R (3 Examples)

The following R code shows how to rename column names of data frames in the R programming language.

Example Data

my_data <- data.frame(x1 = 1:3,
                      x2 = letters[1:3],
                      x3 = "X")
my_data
# x1 x2 x3
#  1  a  X
#  2  b  X
#  3  c  X

Example 1: Change Column Name of One Specific Column

colnames(my_data)[colnames(my_data) == "x1"] <- "y1"
my_data
# y1 x2 x3
#  1  a  X
#  2  b  X
#  3  c  X

Example 2: Change Column Names of All Columns

colnames(my_data) <- c("z1", "z2", "z3")
my_data
# z1 z2 z3
#  1  a  X
#  2  b  X
#  3  c  X

Example 3: Change Column Names of Some Columns

colnames(my_data)[colnames(my_data) %in% c("z1", "z3")] <- c("a1", "a3")
my_data
# a1 z2 a3
#  1  a  X
#  2  b  X
#  3  c  X

Video Examples

YouTube

By loading the video, you agree to YouTube’s privacy policy.
Learn more

Load video

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top