[R] How to join matrices of different row length from a list

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Thu Jan 6 12:23:09 CET 2011


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)))))


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/



More information about the R-help mailing list