R: convert an asymmetric list to a matrix - the number of elements in each sub-list varies

I have an asymmetric list, i.e. the number of items in each sub-list is different. How to convert a list to a matrix?

Below I start with a symmetric list and convert it to a matrix in 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 required 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
+5
source share
1 answer

First, expand each vector in your list with NA to get vectors of the same length. Then create your matrix. For instance:

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

All Articles