I have 60 matrices in R named as mat1, mat2....mat60 and I would like to combine them into a big matrix using rbind. I know that I could write something like
I think this question really relates to the OP having to type out the names of the matrices manually. You can use mget
to return the matrices in a list and then use do.call
and rbind
as posed by @Michele like this (assuming the matrices are located in the .GlobalEnv
):
matList <- mget(paste0("mat",1:60),env=globalenv())
bigm <- do.call("rbind" , matList)
I supposed they all have same number of column (and same colnames
). If so, try this:
do.call("rbind", matlist)
otherwise:
matlist <- lapply(matlist, as.data.frame)
library(plyr)
rbind.fill(matlist)
EDIT:
adding some timings:
lst <- list()
for(i in 1:1000)
lst[[i]] <- matrix(rnorm(10000, 100))
f1 <- function()
do.call("rbind", lst)
f2 <- function(){
lst <- lapply(lst, as.data.table)
rbindlist(lst)
}
library(data.table)
library(microbenchmark)
> microbenchmark(f1(), f2())
Unit: milliseconds
expr min lq median uq max neval
f1() 53.78661 55.22728 63.43546 66.08829 103.1996 100
f2() 210.46232 215.32043 217.93846 221.35012 333.2758 100
If the OP has got his data in matrices I thought that including lst <- lapply(lst, as.data.table)
was the correct way of comparison. Otherwise it would be:
> lst.dt <- lapply(lst, as.data.table)
> f2 <- function(){
+ rbindlist(lst.dt)
+ }
> microbenchmark(f1(), f2())
Unit: milliseconds
expr min lq median uq max neval
f1() 49.00308 50.28515 54.98947 60.71945 87.66487 100
f2() 24.23454 28.57692 31.79278 32.75494 63.78825 100
This should be faster:
library(data.table)
rbindlist(matList)
EDIT The above solution will work for list of data.frame or list, If you have a list of matrix you should convert them before:
rbindlist(lapply(ll,as.data.frame))