Reputation: 153251
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?
Upvotes: 11
Views: 3387
Reputation: 675
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
Upvotes: 17
Reputation: 176648
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" ...
Upvotes: 0
Reputation: 109844
use the argument drop = FALSE as in:
mtcars[, 1, drop = FALSE]
Upvotes: 6