tags:

views:

249

answers:

2

Take the following code:

foo <- list()
foo[[1]] <- list(a=1, b=2)
foo[[2]] <- list(a=11, b=22)
foo[[3]] <- list(a=111, b=222)
result <- do.call(rbind, foo)
result[,'a']

In this case, result[,'a'] shows a list. Is there a more elegant way such that result is a "regular" matrix of vectors? I imagine there are manual ways of going about this, but I was wondering if there was an obvious step that I was missing.

A: 

One possible solution is as follows (but am interested in alternatives):

new.result <- matrix(unlist(result), ncol=ncol(result), 
              dimnames=list(NULL, colnames(result)))
andrewj
+1  A: 

do.call on lists is very elegant, and fast. In fact do.call(rbind, my.list) once saved my ass when I needed to combine a huge list. It was by far the fastest solution.

To solve your problem, maybe something like:

do.call(rbind, lapply(foo, unlist))


> result.2 <- do.call(rbind, lapply(foo, unlist))
> result.2
       a   b
[1,]   1   2
[2,]  11  22
[3,] 111 222
> result.2[, 'a']
[1]   1  11 111
>
Vince
I wish `do.call` + `rbind` was fast. Have you ever tried using it with 10,000 data frames in a list?!
hadley
@hadley: I seem to remember learning in a computation statistics class that this was the fastest way (after many other failed attempts) to bind lists. Maybe I'm remembering the wrong thing. What's faster?
Vince
You can manage about 4x faster if you carefully write it yourself. `rbind.fill` in the next release of plyr will incorporate my latest best efforts.
hadley
This is a pretty interesting discussion; I discovered this comparison: http://www.biostat.wustl.edu/archives/html/s-news/2000-01/msg00169.html. My faith in do.call has been shattered! Thanks hadley.
Vince