简体   繁体   中英

R convert data.frame to list by column

I would like to convert a data.frame into a list of data.frames by column using base R functions and holding the first column constant. For example, I would like to split DF into a list of three data.frames, each of which includes the first column. That is, I would like to end up with the list named LONG without having to type out each list element out separately. Thank you.

DF <- data.frame(OBS=1:10,HEIGHT=rnorm(10),WEIGHT=rnorm(10),TEMP=rnorm(10))
DF

LONG <- list(HEIGHT = DF[c("OBS", "HEIGHT")],
             WEIGHT = DF[c("OBS", "WEIGHT")],
             TEMP   = DF[c("OBS", "TEMP"  )])

LONG

SHORT <- as.list(DF)
SHORT

SPLIT <- split(DF, col(DF))

We can loop through the names of 'DF' except the first one, cbind the first column with the subset of 'DF' from the names .

setNames(lapply(names(DF)[-1], function(x) cbind(DF[1], DF[x])), names(DF)[-1])

Or another option would be

Map(cbind, split.default(DF[-1], names(DF)[-1]), OBS=DF[1])

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