colnames()
KyraThompson67 total contributions
Published Oct 7, 2022
Contribute to Docs
The colnames()
function returns or sets the names of the columns in a data frame.
Syntax
The column names can be retrieved and set using the following syntax:
# Retrival
colnames(df_object)
# Setting
colnames(df_object) <- value
- The
df_object
parameter is the object passed into thecolnames()
function. - The
value
is a vector containing column names; its length must be equal to the amount of columns in the originaldf_object
.
Example
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")colnames(df)
This returns the following:
[1] "Date" "Time" "Total" "Card"
The column names can be changed as follows:
# Reading CSV filedf <- read.csv("transactions.csv")# Change column namescolnames(df) <- c("day", "hour", "subamount", "member")# Retrieve column namescolnames(df)
The above yields the data with the new column names:
[1] "day" "hour" "subamount" "member"
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.