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

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Thu May 17 16:02:08 CEST 2001

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

> The result should be e.g. a data frame like:
> final
>    A  B
> 1 "x" 2
> 2 "y" 4
> Of course I would also love to hear a completely different approach
> but the requirement would be that I want to map a function over a 
> list of data frames and collect multi-valued results (with different
> types) into the ROWS of a new data frame.
> I hesitate to do this with all sorts of loops since I love the
> way of R of NOT doing it with loops.
> Another issue is that I want to do this with quite a lot of
> data, so it should be efficient.
> Too long a question?

It isn't easy (and the habits that data.frame has of making character
columns into factors and trying to be helpful with column names are
not making things easier). The best I can come up with is 

> 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

You want to give cl a names attribute for reasons you will discover by
omitting it...

The crucial thing is that you want the list that as.data.frame sees to
have names, so alternatively,

> l <- lapply(1:2,function(i)sapply(result,"[[",i))
> names(l) <- c("a","b")
> as.data.frame(l)
  a b
x x 2
y y 4

   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