How to print R Dataframe column names values?

You can list your R DataFrame column names by using the following methods:

R base:

column_names <- names(interviews)

Using dplyr:

library (dplyr)

column_names <- interviews %>%
  names()

Using tidyverse:

library(tidyverse)

column_names <- names(select(interviews, everything()))

Using janitor:

library(janitor)

column_names <- get_column_names(interviews)

Get R column names – Practical Example

Define sample DataFrame

Run the following snippet in your R studio environment to create a DataFrame that we’ll use for this tutorial:

month <- c ('December', 'October', 'November', 'July', 'June', 'July')
office <- c ('Osaka', 'Toronto', 'New York', 'Los Angeles', 'Rio de Janeiro', 'Bangalore')
language <- c ('Python', 'Javascript', 'Java', 'R', 'Java', 'Javascript')
salary <- c (149, 156, 138, 213, 105, 176)
interviews <- data.frame (month = month, office = office, language = language, salary = salary)

List column names with R Base

We can use the following R studio to get the column names and convert to a list:

column_names <- as.list(names(interviews))

We can easily browse the list of column values in the RStudio environment tab

Write list of DataFrame columns with dplyr

You can use Dplyr to fetch the column names using the following snippet:

library (dplyr)

column_names <- interviews %>%
  names()

print(column_names)

We’ll get the following character string:

[1] "month"    "office"   "language" "salary" 

Fetch list of columns with tidyverse

To extract the column names, we can also use the tidyverse select function as shown below:

library(tidyverse)

column_names <- names(select(interviews, everything()))

print (column_names)

We will get a similar result as shown above.

Remember: Make sure to install the tidyverse library (or any other 3rd party package) before invoking it in your R script.