How do I make a matrix from a list of vectors in R? How do I make a matrix from a list of vectors in R? r r

How do I make a matrix from a list of vectors in R?


One option is to use do.call():

 > do.call(rbind, a)      [,1] [,2] [,3] [,4] [,5] [,6] [1,]    1    1    2    3    4    5 [2,]    2    1    2    3    4    5 [3,]    3    1    2    3    4    5 [4,]    4    1    2    3    4    5 [5,]    5    1    2    3    4    5 [6,]    6    1    2    3    4    5 [7,]    7    1    2    3    4    5 [8,]    8    1    2    3    4    5 [9,]    9    1    2    3    4    5[10,]   10    1    2    3    4    5


simplify2array is a base function that is fairly intuitive. However, since R's default is to fill in data by columns first, you will need to transpose the output. (sapply uses simplify2array, as documented in help(sapply).)

> t(simplify2array(a))      [,1] [,2] [,3] [,4] [,5] [,6] [1,]    1    1    2    3    4    5 [2,]    2    1    2    3    4    5 [3,]    3    1    2    3    4    5 [4,]    4    1    2    3    4    5 [5,]    5    1    2    3    4    5 [6,]    6    1    2    3    4    5 [7,]    7    1    2    3    4    5 [8,]    8    1    2    3    4    5 [9,]    9    1    2    3    4    5[10,]   10    1    2    3    4    5


Not straightforward, but it works:

> t(sapply(a, unlist))      [,1] [,2] [,3] [,4] [,5] [,6] [1,]    1    1    2    3    4    5 [2,]    2    1    2    3    4    5 [3,]    3    1    2    3    4    5 [4,]    4    1    2    3    4    5 [5,]    5    1    2    3    4    5 [6,]    6    1    2    3    4    5 [7,]    7    1    2    3    4    5 [8,]    8    1    2    3    4    5 [9,]    9    1    2    3    4    5[10,]   10    1    2    3    4    5