I have an asymmetric list, i.e., the number of elements in each sub-list differ. How can I convert the list to a matrix?
Below I begin with a symmetric list and convert it to a matrix two different ways.
# create a symmetric list
my.list1 <- list(c(1,2,3,4),c(5,6,7,8),c(9,10,11,12))
my.list1
# convert symmetric list to a matrix
mat.a1 <- matrix( unlist(my.list1), nrow=length(my.list1), byrow=T )
mat.a1
# alternative method to convert symmetric list to a matrix
mat.b1 <- do.call(rbind, my.list1)
mat.b1
Next I create an asymmetric list:
# create an asymmetric list
my.list2 <- list(c(1,2,3,4),c(5,6,7,8,9),c(10,11,12,13))
my.list2
Here is the desired matrix:
# desired result
# [,1] [,2] [,3] [,4] [,5]
# [1,] 1 2 3 4 NA
# [2,] 5 6 7 8 9
# [3,] 10 11 12 13 NA