r - 如何在 R 中快速组合 60 个矩阵

标签 r matrix

我在 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/

相关文章:

r - 使用首先处理的年份创建新变量

r - r 中数据框不同行的每一列的最大值

c - 在C中定义一个函数以从用户处获取二维矩阵的元素

android - Android 平板电脑随机调整大小问题

R mlr - 从训练数据子集和整个测试数据(不是整个训练数据)创建学习曲线?

r - 经度和纬度的城市名称

R 热图着色取决于高于或低于零的值

python - NumPy linalg.eigh 返回不正确的特征向量

python - 将 numpy 矩阵相加

matlab - 以 2 为底的矩阵对数