# [R] list to matrix

Prof Brian D Ripley ripley at stats.ox.ac.uk
Thu Feb 10 12:51:34 CET 2000

```On Thu, 10 Feb 2000 cstrato at EUnet.at wrote:

> Dear R-users
>
> This seems to be a trivial problem but at the moment I don´t know how to
> solve it.
>
> I have a list with 7000 matrices, every matrix has 2 columns but
> different row-sizes.
> Now I want to combine all lists into one matrix with 2 columns. I would
> have to write:
>
> ma <- rbind(list[[1]],list[[2]], and so on) (this works fine for lists
> with few matrices)
>
> Since it is not possible to write:
>           ma <- rbind(list[[1:7000]]) or
>           ma <- rbind(list[[1]]:list[[7000]])
> maybe someone could tell me how to do it?

You could use do.call("rbind", list), but for efficiency, something like

nr <- sapply(list, NROWS)  # to get a vector of the numbers of rows.
cs <- cumsum(nr)
st <- c(0, nr[-length(nr)]) + 1
res <- matrix(, sum(nr), 2)
for(i in seq(along=nr)) res[st[i]:en[i],] <- list[[i]]

Beware: untested code.

Or, a lot sneakier but probably a lot quicker than either

row1 <- lapply(list, function(x) x[, 1])
row2 <- lapply(list, function(x) x[, 2])
matrix(c(unlist(row1), unlist(row2)),,2)

--
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```