Home » R Tutorials » Get the Columns of Data Frame in R

Get the Columns of Data Frame in R

Data Frame in R is a two-dimensional array or table. Rows in the data frame are observations and columns in the data frame are variables. Using the colnames() and names() function in R,we can get the columns of data frame.

colnames() function in R is used to get the columns from the matrix like ie.. data frame.

names() function in R gets the name of R object in our case it is a data frame.

In this tutorial, we will discuss how to get the list of columns of a data frame in R using colnames() and names() functions in R.

Get the Columns of Data Frame in R using colnames

Using the colnames() function in R, we can get the columns from the data frame.

Let’s practice with an example to extract the column names from the data frame.

Create a data frame in R using the data.frame function in R.

# Create a data frame
student_info <- data.frame(
  name = c("Tom","Kim","Sam","Julie","Emily","Chris"),
  age = c(20,21,19,20,21,22),
  gender = c('M','F','M','F','F','M'),
  marks = c(72,77,65,80,85,87)
)
# Print data frame
student_info

In the above R code, it creates a data frame that has a name, age, gender, and marks as columns.

Get columns of a data frame in R using colnames, use the following code.

# Get the columns from the data frame
colnames(student_info)
[1] "name"   "age"    "gender" "marks" 

colnames() function in R gets the columns from the data frame.

Get the Column names of Data Frame in R using names()

Using the names() function in R, we can get the column names from the data frame in R.

Let’s practice with the example to get the names of the R objects.

# Get the names of data frame object
names(student_info)
[1] "name"   "age"    "gender" "marks" 

names() function in R gets the column names of the data frame object.

Conclusion

I hope the above article to get columns of the data frame in R is helpful to you.

Using the colnames() and names() function in R, we can extracts the columns of the data frame.

Leave a Comment