10

Normally when you get a column, it is a vector. How can I keep it as the data.frame with the same row names and corresponding column name?

RNA
  • 146,987
  • 15
  • 52
  • 70
  • possible duplicate of [1-dimensional Matrix is changed to a vector in R](http://stackoverflow.com/questions/9949202/1-dimensional-matrix-is-changed-to-a-vector-in-r) – joran Apr 06 '12 at 19:08
  • @joran Sorry didn't see the possible duplicate. I'll leave my response and if this question is closed removal of my answer is a moot point. – Tyler Rinker Apr 06 '12 at 19:10
  • @TylerRinker Don't worry about it. This is just a really common question, that's all. – joran Apr 06 '12 at 19:35

3 Answers3

16

Instead of calling the desired column with a comma i.e. data.frame[,i] use data.frame[i] to preserve the class as data.frame and also retain row names.

data.frame[,i] #As a vector
data.frame[i] #As a data.frame
Thraupidae
  • 665
  • 2
  • 5
  • 14
6

use the argument drop = FALSE as in:

mtcars[, 1, drop = FALSE]
Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519
0

If you specify a single number when subsetting a data.frame, you get a one-column data.frame. This is different than matrix subsetting, which requires a "missing" i argument to return the entire column (which it then converts to a vector).

# mtcars is a data.frame
mtcars[1]       # first column
str(mtcars[1])  # is still a data.frame
# 'data.frame':   32 obs. of  1 variable:
#  $ mpg: num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
# MTCARS is a matrix
MTCARS <- as.matrix(mtcars)
as.matrix(MTCARS)[1]        # only the first element
# [1] 21
str(as.matrix(MTCARS)[,1])  # the first column, as a vector
 Named num [1:32] 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 - attr(*, "names")= chr [1:32] "Mazda RX4" "Mazda RX4 Wag" "Datsun 710" ...
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418