我在 R 中有 60 个矩阵,分别命名为 mat1、mat2....mat60,我想使用 rbind 将它们组合成一个大矩阵。我知道我可以写类似的东西
matList <- list(mat1, mat2, ... mat60)
rbind(matList)
但这似乎是一个非常愚蠢的解决方案。知道如何简化流程吗?
最佳答案
我假设它们都有相同数量的列(和相同的 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
关于r - 如何在 R 中快速组合 60 个矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17306162/