Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract column name to vector by calling the column name

Tags:

dataframe

r

We have a data.framehere:

df <- data.frame(x1=rnorm(20),x2=rnorm(20),x3=rnorm(20),x4=rnorm(20),x5=rnorm(20),x6=rnorm(20),x7=rnorm(20),x8=rnorm(20),x9=rnorm(20),x10=rnorm(20),x11=rnorm(20),x12=rnorm(20),x13=c(2,1,1,2,2,1,2,1,2,2,1,1,2,1,2,2,1,2,1,1))

I know I can view the column names easily with

colnames(df)
[1] "x1"  "x2"  "x3"  "x4"  "x5"  "x6"  "x7"  "x8"  "x9"  "x10" "x11" "x12" "x13"

Which prints the line above.

I can also get the name of a single column with colnames(df[...]), for an example

colnames(df[2])
[1] "x2"

I can't seem to figure out how to extract a single column name by calling colnames() with the name of the column, like

colnames(df$x2)
NULL

I bet the solution is ridiculously simple, but I just haven't found any useful information regarding this issue.

like image 833
Olli J Avatar asked Jun 05 '15 10:06

Olli J


1 Answers

Single brackets produce a subset of the data frame with just a single column. The new data frame therefore has a name for its one and only column.

> class(df[2])
[1] "data.frame"
> colnames(df[2])
[1] "x2"

Double brackets [[ or dollar $ extracts the contents of a single column, which in your case is a numeric. It therefore doesn't have any column names, because it is not a data frame.

> class(df$x2)
[1] "numeric"

If you want the name of only the second column you should do

> colnames(df)[2]
[1] "x2"
like image 105
Backlin Avatar answered Nov 12 '22 23:11

Backlin