Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the name of one column by index in R

Tags:

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

like image 261
Agathe Avatar asked Oct 27 '25 05:10

Agathe


1 Answers

simply

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

or

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

or

names(df[1])
  [1] "name"
like image 60
Elia Avatar answered Oct 28 '25 21:10

Elia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!