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

Gabor Grothendieck ggrothendieck at gmail.com
Thu Jan 6 17:10:37 CET 2011

```On Thu, Jan 6, 2011 at 5:56 AM, emj83 <stp08emj at shef.ac.uk> 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)
>

One reasonably simple approach is to convert your matrices to time
series (either ts series or zoo series) as cbind.ts and cbind.zoo both
NA fill.

L <- list(matrix(1:4, 2, 2), matrix(1:6, 3, 2), matrix(2:1, 1, 2))

# using ts
M <- unclass(do.call(cbind, lapply(L, ts)))
tsp(M) <- colnames(M) <- NULL

# With zoo its slightly shorter:

library(zoo)
M <- coredata(do.call(cbind, lapply(L, zoo)))
colnames(M) <- NULL

We can omit the colnames(M) <- NULL part in both cases if the list
itself or the constituent matrices have column names, e.g.

L <- list(A = matrix(1:4, 2, 2), B = matrix(1:6, 3, 2), C = matrix(2:1, 1, 2))

# or

L <- list(cbind(a = 1:2, b = 3:4), cbind(c = 1:3, d = 4:6), cbind(e = 2, f = 1))

--
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com

```