2

我在 R 中有 60 个矩阵,命名为 mat1, mat2....mat60,我想使用 rbind 将它们组合成一个大矩阵。我知道我可以写类似的东西

matList <- list(mat1, mat2, ... mat60)
rbind(matList)

但这似乎是一个非常愚蠢的解决方案。知道如何简化流程吗?

4

3 回答 3

13

我认为它们都有相同数量的列(并且相同colnames)。如果是这样,试试这个:

do.call("rbind", matlist)

否则:

matlist <- lapply(matlist, as.data.frame)

library(plyr)
rbind.fill(matlist)

编辑:

添加一些时间:

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

如果 OP 在矩阵中获得了他的数据,我认为包含lst <- lapply(lst, as.data.table)是正确的比较方式。否则它将是:

> 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
于 2013-06-25T19:48:51.890 回答
8

我认为这个问题确实与 OP 必须手动输入矩阵的名称有关。您可以使用mget返回列表中的矩阵,然后使用do.callandrbind由@Michele 提出,如下所示(假设矩阵位于 中.GlobalEnv):

matList <- mget(paste0("mat",1:60),env=globalenv())
bigm <- do.call("rbind" , matList)
于 2013-06-25T20:47:55.657 回答
6

这应该更快:

 library(data.table)
 rbindlist(matList)

编辑 上述解决方案适用于 data.frame 或列表列表,如果您有矩阵列表,则应先转换它们:

 rbindlist(lapply(ll,as.data.frame))
于 2013-06-25T19:51:43.587 回答