Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R convert data.frame to list by column

Tags:

list

dataframe

r

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))
like image 368
user1491868 Avatar asked Jun 05 '16 15:06

user1491868


1 Answers

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])
like image 131
akrun Avatar answered Oct 19 '22 18:10

akrun