[R] Convert a list to matrix
jim holtman
jholtman at gmail.com
Sun Feb 22 04:32:10 CET 2009
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?
More information about the R-help
mailing list