Get all the Column Names in a DataFrame in R

Here are 3 ways to retrieve all the column names in a DataFrame in R:

(1) Using the names() function:

column_names <- names(df)

(2) Using the colnames() function:

column_names <- colnames(df)

(3) Using the str() function which shows the DataFrame structure, including the column names:

str(df)

Examples of Getting the Column Names in a DataFrame in R

Here is a simple DataFrame in R with 3 columns:

df <- data.frame(product = c("computer", "monitor", "keyboard", "printer", "tablet"),
                 price = c(800, 450, 100, 150, 300),
                 brand = c("A", "B", "C", "X", "Y")
                 )

print(df)

The resulted DataFrame:

   product  price  brand
1 computer    800     A
2  monitor    450     B
3 keyboard    100     C
4  printer    150     X
5   tablet    300     Y

The goal is to retrieve all the column names of this DataFrame.

(1) Using the names() function

Using the names() function:

df <- data.frame(product = c("computer", "monitor", "keyboard", "printer", "tablet"),
                 price = c(800, 450, 100, 150, 300),
                 brand = c("A", "B", "C", "X", "Y")
                 )

column_names <- names(df)

print(column_names)

The resulted column names:

"product"  "price"  "brand"

(2) Using the colnames() function

Using the colnames() function:

df <- data.frame(product = c("computer", "monitor", "keyboard", "printer", "tablet"),
                 price = c(800, 450, 100, 150, 300),
                 brand = c("A", "B", "C", "X", "Y")
                 )

column_names <- colnames(df)

print(column_names)

The result:

"product"  "price"  "brand" 

(3) Using the str() function

Using the str() function:

df <- data.frame(product = c("computer", "monitor", "keyboard", "printer", "tablet"),
                 price = c(800, 450, 100, 150, 300),
                 brand = c("A", "B", "C", "X", "Y")
                 )

str(df)

The result:

'data.frame':   5 obs. of  3 variables:
 $ product: chr  "computer" "monitor" ...
 $ price  : num  800 450 100 150 300
 $ brand  : chr  "A" "B" "C" "X" ...