adschai at optonline.net
2007-Aug-20 01:13 UTC
[R] how to collapse a list of 1 column matrix to a matrix?
Hi, I encounter a situation where I have a list whose element is a column matrix. Says, $'1' [,1] 1 2 3 $'2' [,1] 4 5 6 Is there fast way to collapse the list into a matrix like a cbind operation in this case? Meaning, the result should be a matrix that looks like: [,1] [,2] [1,] 1 4 [2,] 2 5 [3,] 3 6 I can loop through all elements and do cbind manually. But I think there must be a simpler way that I don't know. Thank you. - adschai
François Pinard
2007-Aug-20 01:33 UTC
[R] how to collapse a list of 1 column matrix to a matrix?
[adschai at optonline.net]>I encounter a situation where I have a list whose element is a column >matrix. Says,>$'1' >[,1] >1 >2 >3>$'2' >[,1] >4 >5 >6>Is there fast way to collapse the list into a matrix like a cbind >operation in this case? Meaning, the result should be a matrix that >looks like:> [,1] [,2] >[1,] 1 4 >[2,] 2 5 >[3,] 3 6>I can loop through all elements and do cbind manually. But I think >there must be a simpler way that I don't know. Thank you.The "do.call" function is the R equivalent of the "apply" from many other languages. I guess that, in R, "apply" was already taken :-) For example:> a = list(x=matrix(1:3, 3, 1), y=matrix(4:6, 3, 1)) > a$x [,1] [1,] 1 [2,] 2 [3,] 3 $y [,1] [1,] 4 [2,] 5 [3,] 6> do.call(cbind, a)[,1] [,2] [1,] 1 4 [2,] 2 5 [3,] 3 6 -- Fran?ois Pinard http://pinard.progiciels-bpi.ca
Gabor Grothendieck
2007-Aug-20 01:48 UTC
[R] how to collapse a list of 1 column matrix to a matrix?
Try this: L <- list(`1` = matrix(1:4, 4), `2` = matrix(5:8, 4)) sapply(L, c) Note that the list component names are kept as column names in the result On 8/19/07, adschai at optonline.net <adschai at optonline.net> wrote:> Hi, > > I encounter a situation where I have a list whose element is a column matrix. Says, > > $'1' > [,1] > 1 > 2 > 3 > > $'2' > [,1] > 4 > 5 > 6 > > Is there fast way to collapse the list into a matrix like a cbind operation in this case? Meaning, the result should be a matrix that looks like: > > [,1] [,2] > [1,] 1 4 > [2,] 2 5 > [3,] 3 6 > > I can loop through all elements and do cbind manually. But I think there must be a simpler way that I don't know. Thank you. > > - adschai > > ______________________________________________ > R-help at 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. >