A dataframe in R is a data structure used to store tabular data in rows and columns. In this tutorial, we will look at how to get the column names of a dataframe in R as a vector.
How do you get the column names in R?

You can use the colnames()
function in R to get the column names of a dataframe. Pass the dataframe as an argument to the function.
The following is the syntax –
colnames(dataframe)
It returns a vector containing the column names of the columns in the dataframe.
Steps to get the column names of an R dataframe
Let’s now look at the steps to follow to get column names of a dataframe
Step 1 – Create a dataframe
First, we will create a dataframe that we will be using throughout this tutorial.
# create a dataframe employees_df = data.frame( "Name"= c("Jim", "Dwight", "Angela", "Tobi", "Kevin"), "Age"= c(26, 28, 29, 32, 30), "Department"= c("Sales", "Sales", "Accounting", "HR", "Accounting") ) # display the dataframe print(employees_df)
Output:
Name Age Department 1 Jim 26 Sales 2 Dwight 28 Sales 3 Angela 29 Accounting 4 Tobi 32 HR 5 Kevin 30 Accounting
We now have a dataframe containing information about some employees working in an office. The dataframe has columns “Name”, “Age”, and “Department”.
Step 2 – Get the column names in the dataframe using colnames()
function
Pass the dataframe as an argument to the colnames()
function to get the dataframe’s column names.
Let’s get the column names of the dataframe created above.
# get column names in the dataframe as vector col_names <- colnames(employees_df) # display the resulting vector print(col_names)
Output:
[1] "Name" "Age" "Department"
We get a vector with the column names in the above dataframe.
You might also be interested in –
- Create a DataFrame in R
- How to Add a Row to a Dataframe in R?
- How to Add a Column to a Dataframe in R?
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.