1

I was wondering why names() or colnames() return the names of at least 2 columns in the data.frame in R?

For example, names(mtcars[, 2]) returns NULL but names(mtcars[, 2:3]), works perfectly ok (i.e., returns "cyl" "disp")?

What to do to get the name of a single column in a data.frame, then?

rnorouzian
  • 7,397
  • 5
  • 27
  • 72

1 Answers1

2

The result of mtcars[,2] is a vector, not a data.frame (because of the default drop = TRUE argument). Use names(mtcars)[2] to get one column name.

Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418