[R] coercing a list into matrix

Steven McKinney smckinney at bccrc.ca
Wed Jan 14 23:40:21 CET 2009


Hi Ken,

If your lists are not too large something such as this can work:

> matrixFromList <- function(listX) t(sapply(listX, function(x, n) c(x, rep(NA, n))[1:n], n = max(sapply(listX, length))))

> matrixFromList(list(c(3,2,3),c(6,5)))
     [,1] [,2] [,3]
[1,]    3    2    3
[2,]    6    5   NA

> A <- list(c(3,2,3), c(1,2,3,4), c(5,6))

> matrixFromList(A)
     [,1] [,2] [,3] [,4]
[1,]    3    2    3   NA
[2,]    1    2    3    4
[3,]    5    6   NA   NA

> class(matrixFromList(A))
[1] "matrix"



Best

Steven McKinney

Statistician
Molecular Oncology and Breast Cancer Program
British Columbia Cancer Research Centre

email: smckinney +at+ bccrc +dot+ ca

tel: 604-675-8000 x7561

BCCRC
Molecular Oncology
675 West 10th Ave, Floor 4
Vancouver B.C. 
V5Z 1L3
Canada




-----Original Message-----
From: r-help-bounces at r-project.org on behalf of Lo, Ken
Sent: Wed 1/14/2009 1:50 PM
To: r-help at r-project.org
Subject: [R] coercing a list into matrix
 
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

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list