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. Thanks, Andrew [[alternative HTML version deleted]]
Gabor Grothendieck
2009-Oct-04 00:01 UTC
[R] converting matrix of lists to a regular matrix
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
> ways of going about this, but I was wondering if there was an obvious 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
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
On Oct 3, 2009, at 7:51 PM, Andrew Yee 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) >Instead, perhaps: > do.call(rbind, lapply(foo, unlist)) a b [1,] 1 2 [2,] 11 22 [3,] 111 222 > do.call(rbind, lapply(foo, unlist))[,"a"] [1] 1 11 111> result <- do.call(rbind, foo) > result[,'a']class(result) # also matrix> > 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.Your example shows that a matrix can be constructed around a list, although I agree with you that this seems a bit unusual. -- David Winsemius, MD Heritage Laboratories West Hartford, CT