Re: [R] list of lists to a data.frame

From: Marc Schwartz (via MN) <mschwartz_at_mn.rr.com>
Date: Sat 19 Aug 2006 - 06:56:42 EST

On Fri, 2006-08-18 at 16:44 -0400, Rajarshi Guha wrote:
> Hi, I have a situation where I have a list of lists. Each list can
> contain elements of different types (but each one will be a scalar) say
> of double, integer or character.
>
> However the elements of each list are always in the same order:
>
> x <- list('a', 1, 2)
> y <- list('b', 3, 4)
> z <- list('c', 5, 6)
>
> a <- list(x,y,z)
>
> What I'd like to do is to convert a to a data.frame.
>
> Currently I am doing:
>
> b <- do.call(rbind, a)
>
> However, when I do b[,1] I get a list returned rather than a vector of
> characters and similarly for b[,2] and so on.
>
> I am clearly missing something, but how do I convert the list of lists
> to a data.frame where a column is represented as a vector rather than a
> list?
>
> Thanks,

How about:

> as.data.frame(sapply(a, rbind))
  V1 V2 V3
1 a b c
2 1 3 5
3 2 4 6

or:

> as.data.frame(t(sapply(a, rbind)))
  V1 V2 V3
1 a 1 2
2 b 3 4
3 c 5 6

depending upon how you wanted the columns versus rows to be structured.

HTH, Marc Schwartz



R-help@stat.math.ethz.ch 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. Received on Sat Aug 19 07:04:30 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Sat 19 Aug 2006 - 08:21:25 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.