[R] Convert a list to matrix

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Sun Feb 22 10:32:41 CET 2009


one way is the following:

m <- list(A = 1, B = 1:2, C = 1:3, D = 1:4)

n <- max(sapply(m, length))
t(sapply(m, function (x) c(x, rep(NA, n - length(x)))))


I hope it helps.

Best,
Dimitris


Daren Tan wrote:
> I would like to convert a list to matrix. This can be easily achieved via
> do.call. The only problem is each element of the list has different length,
> which causes the recycling of values. How can I have NA instead of recycled
> values ?
> 
> m <- list()
> m[["A"]] <- 1
> m[["B"]] <- 2:3
> do.call(rbind, m)
>   [,1] [,2]
> A    1    1
> B    2    3
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> 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.
> 

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014




More information about the R-help mailing list