gpt4 book ai didi

r - 取消列出大型矩阵列表的更快方法?

转载 作者:行者123 更新时间:2023-12-04 16:33:30 25 4
gpt4 key购买 nike

我有一个大型矩阵列表。所有这些矩阵都有相同的行数,我想“取消列出”它们并将它们的所有列绑定(bind)在一起。下面是我写的一段代码,但我不确定这是否是我在计算效率方面能达到的最好的。

# simulate
n <- 10
nr <- 24
nc <- 8000
test <- list()
set.seed(1234)
for (i in 1:n){
test[[i]] <- matrix(rnorm(nr*nc),nr,nc)
}

> system.time( res <- matrix( as.numeric( unlist(test) ) ,nr,nc*n) )
user system elapsed
0.114 0.006 0.120

最佳答案

要处理列表并对所有对象调用函数,do.call是我通常的第一个想法,以及 cbind这里按列绑定(bind)所有对象。

对于 n=100 (为了完整起见,还有其他答案):

n <- 10
nr <- 24
nc <- 8000
test <- list()
set.seed(1234)
for (i in 1:n){
test[[i]] <- matrix(rnorm(nr*nc),nr,nc)
}

require(data.table)
ori <- function() { matrix( as.numeric( unlist(test) ) ,nr,nc*n) }
Tensibai <- function() { do.call(cbind,test) }
BrodieG <- function() { `attr<-`(do.call(c, test), "dim", c(nr, nc * n)) }
nicola <- function() { setattr(unlist(test),"dim",c(nr,nc*n)) }

library(microbenchmark)
microbenchmark(r1 <- ori(),
r2 <- Tensibai(),
r3 <- BrodieG(),
r4 <- nicola(), times=10)

结果:
Unit: milliseconds
expr min lq mean median uq max neval cld
r1 <- ori() 23.834673 24.287391 39.49451 27.066844 29.737964 93.74249 10 a
r2 <- Tensibai() 17.416232 17.706165 18.18665 17.873083 18.192238 21.29512 10 a
r3 <- BrodieG() 6.009344 6.145045 21.63073 8.690869 10.323845 77.95325 10 a
r4 <- nicola() 5.912984 6.106273 13.52697 6.273904 6.678156 75.40914 10 a

至于为什么(在评论中),@nicola 确实给出了答案,副本比原始方法少。

所有方法都给出相同的结果:
> identical(r1,r2,r3,r4)
[1] TRUE

关于r - 取消列出大型矩阵列表的更快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35945024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com