Dear list, I have a list of number sequences. Each number sequence has different numbers of elements. Is there a quick way (other than to iterate through the entire list) way to coerce list to matrix with NAs filling in the short sequences? An example of what I mean is this: A <- list(c(3,2,3),c(6,5)) I'd like to get A so that it is 3 2 3 6 5 NA Best, Ken
coercing a list into matrix
2 messages · Lo, Ken, Marc Schwartz
on 01/14/2009 03:50 PM Lo, Ken wrote:
Dear list, I have a list of number sequences. Each number sequence has different numbers of elements. Is there a quick way (other than to iterate through the entire list) way to coerce list to matrix with NAs filling in the short sequences? An example of what I mean is this: A <- list(c(3,2,3),c(6,5)) I'd like to get A so that it is 3 2 3 6 5 NA
A "quick and dirty" two step approach: # Get the max length of the vectors in 'A' L.max <- max(sapply(A, length), na.rm = TRUE) # Now extract each vector from 'A', appending an appropriate # number of NA's to fill out the vector
t(sapply(A, function(x) c(x, rep(NA, L.max - length(x)))))
[,1] [,2] [,3] [1,] 3 2 3 [2,] 6 5 NA HTH, Marc Schwartz