Get the name of one column by index in R

Viewed 676

Imagine the following dataframe df:

name <- c("Jon", "Bill", "Maria")
age <- c(23, 41, 32)
df <- data.frame(name, age)

I want to be able to get the name of a column using its index.

If I try and get the names of multiple columns, it is fine:

colnames(df[,c(1,2)])
[1] "name" "age" 

However, when I try to get only one, say the first, it is not working as I would expect:

colnames(df[,1])
NULL

What is that and how can I get the name of my first column "name"?

3 Answers

simply

colnames(df)[1]
[1] "name"

or

colnames(df[1])
[1] "name"

or

names(df[1])
  [1] "name"

You can enable drop = FALSE

> colnames(df[,1,drop = FALSE])
[1] "name"

or

> colnames(df[1])              
[1] "name"

You may also assign a new column name,

colnames(df)[1] 
colnames(df)[1] <- c("Newname");df
colnames(df) <- c( "Name", "Age");df
Related