简体   繁体   中英

how to get each column as data.frame (instead of a vector) from a data.frame?

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?

Instead of calling the desired column with a comma ie 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

use the argument drop = FALSE as in:

mtcars[, 1, drop = FALSE]

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" ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM