R: convert asymmetric list to matrix - number of elements in each sub-list differ
r
Solution
First, extend each vector in your list with NAs to get vectors of the same length. Then create your matrix. For example:
max.len <- max(sapply(my.list2, length))
corrected.list <- lapply(my.list2, function(x) {c(x, rep(NA, max.len - length(x)))})
mat <- do.call(rbind, corrected.list)
Problem
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 ```