The colnames() function returns or sets the names of the columns in a data frame.


The column names can be retrieved and set using the following syntax:

# Retrival

# Setting
colnames(df_object) <- value
  • The df_object parameter is the object passed into the colnames() function.
  • The value is a vector containing column names; its length must be equal to the amount of columns in the original df_object.


The following example uses a CSV file named "transactions.csv" file with the following information in it:

Date Time Total Card
15-08-2022 9:20 120.83 Yes
08-08-2022 19:17 73.4 No
30-07-2022 13:05 15.93 Yes
22-07-2022 11:30 6.99 Yes

The column names can be retrieved by reading the file and using the colnames() function:

df <- read.csv("transactions.csv")

This returns the following:

[1] "Date" "Time" "Total" "Card"

The column names can be changed as follows:

# Reading CSV file
df <- read.csv("transactions.csv")
# Change column names
colnames(df) <- c("day", "hour", "subamount", "member")
# Retrieve column names

The above yields the data with the new column names:

[1] "day" "hour" "subamount" "member"


Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn R on Codecademy