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"?
simply
colnames(df)[1]
[1] "name"
or
colnames(df[1])
[1] "name"
or
names(df[1])
[1] "name"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With