[R] How to join matrices of different row length from a list
David Winsemius
dwinsemius at comcast.net
Thu Jan 6 16:32:23 CET 2011
On Jan 6, 2011, at 6:23 AM, Dimitris Rizopoulos wrote:
> try this:
>
> matLis <- list(matrix(1:4, 2, 2), matrix(1:6, 3, 2),
> matrix(2:1, 1, 2))
>
> n <- max(sapply(matLis, nrow))
> do.call(cbind, lapply(matLis, function (x)
> rbind(x, matrix(, n-nrow(x), ncol(x)))))
It's good that you solved the OP's question so neatly, since the
alternate solution I was going to propose turns out to be for a
different problem. Had the problem been for binding by row and padding
with NA's, there is a ready-made function in the plyr package,
rbind.fill.matrix(). No cbind.fill or cbind.fill.matrix, yet. It looks
as though switching the roles of column and row in either of your
respective solutions could create a general solution though.
--
David.
>
>
> I hope it helps.
>
> Best,
> Dimitris
>
>
> On 1/6/2011 11:56 AM, emj83 wrote:
>>
>> Hi,
>>
>> I have several matrix in a list, for example:
>> e
>> [[1]]
>> [,1] [,2]
>> [1,] 1 3
>> [2,] 2 4
>>
>> [[2]]
>> [,1] [,2]
>> [1,] 1 4
>> [2,] 2 5
>> [3,] 3 6
>>
>> [[3]]
>> [,1] [,2]
>> [1,] 2 1
>>
>> I would like to join them by column i.e.
>> [,1] [,2] [,3] [,4][,5] [,6]
>> [1,] 1 3 1 4 2 1
>> [2,] 2 4 2 5 NA NA
>> [3,] NA NA 3 6 NA NA
>>
>> I have tried do.call(cbind,e) but I get this error message as the
>> rows are
>> of different length-
>> Error in function (..., deparse.level = 1) :
>> number of rows of matrices must match (see arg 2)
>>
>> Can anyone advise me please?
>>
>> Thanks Emma
>>
>>
>
> --
> Dimitris Rizopoulos
> Assistant Professor
> Department of Biostatistics
> Erasmus University Medical Center
>
> Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
> Tel: +31/(0)10/7043478
> Fax: +31/(0)10/7043014
> Web: http://www.erasmusmc.nl/biostatistiek/
>
> ______________________________________________
> 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.
David Winsemius, MD
West Hartford, CT
More information about the R-help
mailing list