How can we extract column name to a vector by calling column name using $ sign in R?

r

#1

Hi,

I created a data frame. ->

df<-data.frame(a=1:5,b=6:10,c=11:15,d=16:20,e=21:25,f=26:30,g=31:35,h=36:40)
df
a b c d e f g h
1 1 6 11 16 21 26 31 36
2 2 7 12 17 22 27 32 37
3 3 8 13 18 23 28 33 38
4 4 9 14 19 24 29 34 39
5 5 10 15 20 25 30 35 40

colnames(df)
[1] “a” “b” “c” “d” “e” “f” “g” “h”

colnames(df[3])
[1] “c”

I get NULL if I use something like ->

colnames(df$d)
NULL

How can I extract the column name using like this?

Thank you.


#2

@mukesh, I’m not quite sure what you’re trying to do here, as you already have the column name (in this case, d).


#3

I want to use colnames() and I want to give the argument in it as df$d and get the output as d. Is this possible and if not then why?


#4

@mukesh
Here’s a tip: I would suggest you to print out only the arguments you have provided, namely df[3] and df$d and see if you notice a difference between the two outputs, and then compare each of it with what ?colnames says about the arguments that function accepts.

If you some other reason why trying to do this, please give us the context so that we can help you with it.