Get Column Names of Data Frame

We can get column names of a data frame in R language, either by using colnames() function or names() function.

To get the column names of a data frame using colnames() function, pass the data frame as an argument to the function, and it return a vector with the column names.

</>
Copy
colnames(data_frame_name)

To get the column names of a data frame using names() function, pass the data frame as an argument to the function, and it return a vector with the column names.

</>
Copy
names(data_frame_name)

Examples

Get Column Names using colnames() Function

In the following example, we take a data frame in df, with three columns, and get the column names using colnames() function.

example.r

</>
Copy
df <- data.frame(name = c('A', 'B', 'C', 'D'),
                 age = c(4, 8, 10, 14),
                 income = c(1.6, 1.5, 1.7, 1.9))

result <- colnames(df)
print(result)

Output

tutorialkart$ Rscript example.r
[1] "name"   "age"    "income"

Get Column Names using names() Function

In the following example, we take a data frame in df, and get the column names using names() function.

example.r

</>
Copy
df <- data.frame(name = c('A', 'B', 'C', 'D'),
                 age = c(4, 8, 10, 14),
                 income = c(1.6, 1.5, 1.7, 1.9))

result <- names(df)
print(result)

Output

tutorialkart$ Rscript example.r
[1] "name"   "age"    "income"

Conclusion

In this R Tutorial, we learned how to get the names of columns in given data frame using colnames() or names() function, with the help of an example programs.