[R] coercing a list into matrix

Marc Schwartz marc_schwartz at comcast.net
Wed Jan 14 23:23:29 CET 2009


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




More information about the R-help mailing list