Joschi
Joschi

Reputation: 3039

Call a specific column name in R

colnames gives me the column names for a whole dataframe. Is there any way to get the name of one specified column. i would need this for naming labels when plotting data in ggplot.

So say my data is like this:

df1 <- data.frame(a=sample(1:50,10), b=sample(1:50,10), c=sample(1:50,10))

I would need something like paste(colnames(df1[,1])) which obviously won't work. any ideas?

Upvotes: 6

Views: 53140

Answers (3)

hiirulainen
hiirulainen

Reputation: 107

Would colnames(df1)[1] solve the problem?

Upvotes: 2

Henry
Henry

Reputation: 6784

names(df1)[1]

will give you the name of the first column. So too will

names(df1[1])

Neither uses a comma.

Upvotes: 2

user1317221_G
user1317221_G

Reputation: 15461

you call the name like this:

colnames(df1)[1] 
# i.e. call the first element of colnames not colnames of the first vector

however by removing your comma e.g.:

colnames(df1[1])

you can also call the names, becauseusing only [x] not [,x] or [[x]] keeps the data.frame structure not reducing to a vector unlike $x and [,x]

Upvotes: 12

Related Questions