3

This might sound trivial, but I am facing an issue in finding column name of a dataframe(with 1 column)

> a <- data.frame(x = c(1,2,3,4,5), y = c("a", "a","c","d","r")) > a x y 1 1 a 2 2 a 3 3 c 4 4 d 5 5 r > colnames(a) [1] "x" "y" > names(a) [1] "x" "y" > a1 <- a[,1] > class(a1) [1] "numeric" > a1 [1] 1 2 3 4 5 > a1 <- as.data.frame(a[,1]) > a1 a[, 1] 1 1 2 2 3 3 4 4 5 5 > colnames(a1) [1] "a[, 1]" > names(a1) [1] "a[, 1]" > 

I am selecting 1 column from the dataframe "a", I want the output to be "x" when I query for the column name of a1. Appreciate help on this. Thanks

2
  • 1
    when you subset 'a' use the drop argument: a1 <- a[,1,drop=FALSE] Commented Apr 18, 2014 at 15:08
  • @user20650 You should write this up as an answer. Commented Apr 18, 2014 at 15:15

2 Answers 2

1
# Data a <- data.frame(x = c(1,2,3,4,5), y = c("a", "a","c","d","r"), z = 1:5) class(a) #[1] "data.frame" # Subset a a1 <- a[,1] class(a1) is.vector(a1) is.data.frame(a1) 

This is a numeric vector called a1 (not x). Look at the drop argument in ?"[": the default is drop =TRUE. As there is only one column, a[,1] is coerced to a numeric vector and the column name is lost. When you subsequently pass the vector to data.frame, the columns will take the name of the vector passed to it (if it is named), hence

names(data.frame(a1)) # [1] "a1" 

So use drop = FALSE when subsetting to avoid the reduction - a1 will be a one column data.frame

(a1 <- a[,1, drop = FALSE]) # x #1 1 #2 2 #... 
Sign up to request clarification or add additional context in comments.

Comments

0

Not sure if this provides any further enlightenment, but it's interesting nonetheless. It seems like this may be how drop = FALSE came about.

> a1 <- structure(data.frame(a[,1]), .Names = names(a)[1]) > colnames(a1) # [1] "x" 

But you could really just do this:

> a1 <- a["x"] > colnames(a1) # [1] "x" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.