We have a data.frame
here:
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.
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"
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