Agathe
Agathe

Reputation: 313

Get the name of one column by index in R

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"?

Upvotes: 4

Views: 6853

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 102700

You can enable drop = FALSE

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

or

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

Upvotes: 0

Elia
Elia

Reputation: 2584

simply

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

or

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

or

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

Upvotes: 9

Related Questions