[R] How to quickly convert a data.frame into a structure of lists

Eik Vettorazzi E.Vettorazzi at uke.uni-hamburg.de
Wed Aug 10 19:04:15 CEST 2011


Hi Frederic,
shouldn't there be an result for the 3rd row as well, eg ls1$b$Y?

Maybe this will do what you want?

dtf<-within(dtf,index<-factor(A:B))
tapply(dtf$C,dtf$index,list)

Hth.

Am 10.08.2011 16:30, schrieb Frederic F:
> Hello Duncan,  
> 
> Here is a small example to illustrate what I am trying to do.
> 
> # Example data.frame
> df=data.frame(A=c("a","a","b","b"), B=c("X","X","Y","Z"), C=c(1,2,3,4)) 
> #   A B C
> # 1 a X 1
> # 2 a X 2
> # 3 b Y 3
> # 4 b Z 4
> 
> ### First way of getting the list structure (ls1) using imbricated lapply
> loops:
> # Get the structure and populate it:
> ls1<-lapply(levels(df$A), function(levelA) { 
>       lapply(levels(df$B), function(levelB) {df$C[df$A==levelA &
> df$B==levelB]})
> })
> # Apply the names:
> names(list_structure)<-levels(df$A)
> for (i in 1:length(list_structure))
> {names(list_structure[[i]])<-levels(df$B)}
> 
> # Result:
> ls1$a$X
> # [1] 1 2
> ls1$b$Z
> # [1] 4
> 
> The data.frame will always be 'complete', i.e., there will be a value in
> every row for every column. 
> I want to produce a structure like this one quickly (I aim at something
> below 10 seconds) for a dataset containing between 1 and 2 millions of rows. 
> 
> I hope that this helps clarify things.
> 
> Thanks for your help,
> 
> Frederic 
> 
> --
> View this message in context: http://r.789695.n4.nabble.com/How-to-quickly-convert-a-data-frame-into-a-structure-of-lists-tp3731746p3733073.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

-- 
Eik Vettorazzi
Institut für Medizinische Biometrie und Epidemiologie
Universitätsklinikum Hamburg-Eppendorf

Martinistr. 52
20246 Hamburg

T ++49/40/7410-58243
F ++49/40/7410-57790



More information about the R-help mailing list