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]]
This should do what you want:> m <- list() > m[["A"]] <- 1 > m[["B"]] <- 2:3 > # get the maximum length > maxLen <- max(sapply(m, length)) > # create a new list with elements padded out with NAs > newM <- lapply(m, function(.ele){+ c(.ele, rep(NA, maxLen))[1:maxLen] + })> do.call(rbind, newM)[,1] [,2] A 1 NA B 2 3>On Sat, Feb 21, 2009 at 10:17 PM, Daren Tan <darentan76 at gmail.com> 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. >-- Jim Holtman Cincinnati, OH +1 513 646 9390 What is the problem that you are trying to solve?
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