[R] list to data frame by rows ...

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Fri May 18 15:43:49 CEST 2001

Johann Petrak <johann at ai.univie.ac.at> writes:

> I am not yet shutting up on this :)
> Thanks for the suggestions ... problem is that the code was
> given as an illustration, in reality do4split would do
> some complicated magic calculations that yield several
> interesting results of mixed type. 
> Peter Dalgaard BSA wrote:
> > 
> > [...]
> > > cl <- 1:2
> > > names(cl) <- c("a","b")
> > > as.data.frame(lapply(cl,function(i)sapply(result,"[[",i)))
> >   a b
> > x x 2
> > y y 4
> > 
> The problem here is that the functionality gets pulled out of 
> do4split which isnt really possible in the *real* situation.

Umm, did I come across as intended there? I'm not "pulling anything
out" of do4split with that code, I'm working on the result of it
(after result <- lapply(splitted, do4split) ). If you have code that
generates a list of lists which all have similar structure (i.e. they
can have mixed type but it must be the same mix for all) then that
kind of code should be able to do the conversion to a data frame. It's
a bit wasteful of storage though, since list storage has a rather
large overhead.

> I would be curious how efficient this is and what actually happens.
> Will ltmp[[i]]<-c(ltmp[[i]],tmp[[i]]) just extend the column or
> will the whole content be copied every time? 

It will be copied, so you do not want to do that...!

It would be a better idea to create a data frame with null values
first and fill the rows with

ltmp[j,] <- lapply(tmp,I)

and you can presumably create ltmp with the right types and length

n <- length(splitted)
ltmp <- data.frame(a=I(character(n)), b=numeric(5))


ltmp <- data.frame(a=I(character(n)), b=numeric(n))
ltmp[1,] <- list(I("x"),2)
ltmp[2,] <- list(I("y"),4)

The I() is necessary because otherwise the data frame assignment code
will try to convert the character on the rhs to a factor which then
gets converted to an integer and then back to a character by one of
the sillier coercion stunts in R:

> x<-"a"
> x[1]<-factor("b")
> x
[1] "1"

(I think there's a reason for it....)  

   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list