I came up with a very similar solution to @Fernandes, using tips from here and here
Recreate your example:
lst <- list(c(86, 101), c(35, 61, 112), c(10, 15))
# [[1]]
# [1] 86 101
#
# [[2]]
# [1] 35 61 112
#
# [[3]]
# [1] 10 15
Figure out the number of rows needed, and then extend each of the vectors to that length:
num_row <- max(sapply(lst, length))
for (i in seq_along(lst)) {
length(lst[[i]]) <- num_row
}
# [[1]]
# [1] 86 101 NA
#
# [[2]]
# [1] 35 61 112
#
# [[3]]
# [1] 10 15 NA
Column bind all the now-equal-length-vectors together into a matrix:
m <- sapply(lst, cbind)
# [,1] [,2] [,3]
# [1,] 86 35 10
# [2,] 101 61 15
# [3,] NA 112 NA
Replace all the NA's with the desired 0's:
m[is.na(m)] <- 0
# [,1] [,2] [,3]
# [1,] 86 35 10
# [2,] 101 61 15
# [3,] 0 112 0
I really wanted to replace the for loop with with some kind of 'apply', but couldn't figure it out. If anyone knows how to not use the for loop, I'd like to see it!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…