Skip to content

Best way to turn a list into a data.frame

4 messages · Hadley Wickham, Luc Villandre, Daniel Brewer

#
Hello,

What is the best way to turn a list into a data.frame?

I have a list with something like:
$`3845`
 [1] "04010" "04012" "04360"

$`1029`
[1] "04110" "04115"

And I would like to get a data frame like the following:

3845 "04010"
3845 "04012"
3845 "04360"
1029 "04110"
1029 "04115"

Any ideas?

Dan
#
On Mon, Apr 6, 2009 at 8:49 AM, Daniel Brewer <daniel.brewer at icr.ac.uk> wrote:
l <- list("3845" = c("a", "b", "c"), "1029" = c("d", "e","f"))

libary(reshape)
melt(l)

Hadley
#
Hi Daniel,

In your case, I guess you could use:

col1 = rep(attributes(my.list)$names,lapply(my.list,length)) ;
col2 = unlist(my.list,use.names=FALSE) ;
my.data.frame = as.data.frame(cbind(col1,col2)) ;

This should work well.

Cheers,

Luc
Daniel Brewer wrote:
#
Thanks thats marvellous.  Does the trick beautifully.

Dan
hadley wickham wrote: