# [R] converting matrix of lists to a regular matrix

Gabor Grothendieck ggrothendieck at gmail.com
Sun Oct 4 02:23:54 CEST 2009

```The object out in my post is identical to the object, result, in your
post.  If that was not what you are looking for some additional
explanation is needed on what it is that you seek.

> M <- matrix(list(1, 11, 111, 2, 22, 222), nc = 2, dimnames = list(NULL, c("a", "b")))
>
> 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)
>
> identical(result, out)
[1] TRUE

On Sat, Oct 3, 2009 at 8:16 PM, Andrew Yee <yee at post.harvard.edu> wrote:
> Gabor, thanks for the reply.
> However, the output of matrix(list(1, 11, 111, 2, 22, 222), nc = 2, dimnames
> = list(NULL, c("a", "b"))) is a matrix of lists.
> foo <- matrix(list(1, 11, 111, 2, 22, 222), nc = 2, dimnames = list(NULL,
> c("a", "b")))
> foo[,'a'] # returns a list
> One possible solution is as follows, though I wonder if this step could be
> avoided in the first place through more careful coding of the preliminary
> steps:
> new.result <- matrix(unlist(result), ncol=ncol(result), dimnames=list(NULL,
> colnames(result)))
> # I use unlist()
> Andrew
> On Sat, Oct 3, 2009 at 8:01 PM, Gabor Grothendieck <ggrothendieck at gmail.com>
> wrote:
>>
>> Try this:
>>
>> matrix(list(1, 11, 111, 2, 22, 222), nc = 2, dimnames = list(NULL, c("a",
>> "b")))
>>
>> or
>>
>> out  <- list(1, 11, 111, 2, 22, 222)
>> dim(out) <- c(3, 2)
>> colnames(out) <- c("a", "b")
>>
>> On Sat, Oct 3, 2009 at 7:51 PM, Andrew Yee <yee at post.harvard.edu> wrote:
>> > 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
>> > step
>> > that I was missing.
>> >
>> > Thanks,
>> > Andrew
>> >
>> >        [[alternative HTML version deleted]]
>> >
>> > ______________________________________________
>> > R-help at r-project.org mailing list
>> > https://stat.ethz.ch/mailman/listinfo/r-help