get dataframe column names in R

R – Get Vector of Dataframe Column Names

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?

get dataframe 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”.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

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 –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Authors

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

  • Gottumukkala Sravan Kumar
Scroll to Top