我在R中有60个矩阵,命名为mat1,mat2 .... mat60,我想用rbind将它们组合成一个大矩阵.我知道我可以写类似的东西
matList <- list(mat1, mat2, ... mat60)
rbind(matList)
Run Code Online (Sandbox Code Playgroud)
但这似乎是一个非常愚蠢的解决方案 知道如何简化流程吗?
Mic*_*ele 13
我猜他们都有相同数量的列(和相同colnames).如果是这样,试试这个:
do.call("rbind", matlist)
Run Code Online (Sandbox Code Playgroud)
除此以外:
matlist <- lapply(matlist, as.data.frame)
library(plyr)
rbind.fill(matlist)
Run Code Online (Sandbox Code Playgroud)
编辑:
添加一些时间:
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
Run Code Online (Sandbox Code Playgroud)
如果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
Run Code Online (Sandbox Code Playgroud)
我认为这个问题确实与OP必须手动输入矩阵的名称有关.您可以使用mget返回列表中的矩阵,然后像@Michele一样使用do.call和rbind假设(假设矩阵位于.GlobalEnv):
matList <- mget(paste0("mat",1:60),env=globalenv())
bigm <- do.call("rbind" , matList)
Run Code Online (Sandbox Code Playgroud)
这应该更快:
library(data.table)
rbindlist(matList)
Run Code Online (Sandbox Code Playgroud)
编辑 上面的解决方案适用于data.frame或list列表,如果你有一个矩阵列表,你应该在之前转换它们:
rbindlist(lapply(ll,as.data.frame))
Run Code Online (Sandbox Code Playgroud)