Wol*_*ker 14 replication r matrix
我有一个矩阵,并寻找一种有效的方法来复制它n次(其中n是数据集中观察的数量).例如,如果我有一个矩阵A.
A <- matrix(1:15, nrow=3)
然后我想要一个表格的输出
rbind(A, A, A, ...) #n times
.
显然,有许多方法来构造这样的大矩阵,例如使用for
循环apply
或类似的函数.然而,对"矩阵复制 - 函数"的调用发生在我的优化算法的核心,在我的程序的一次运行中它被称为数万次.因此,循环,应用类型的函数和类似的东西都不够有效.(这样的解决方案基本上意味着n上的循环执行了数万次,这显然是低效的.)我已经尝试使用普通rep
函数,但还没有找到一种方法来排列rep
矩阵的输出所需格式.
该解决方案
do.call("rbind", replicate(n, A, simplify=F))
效率太低,因为rbind
在这种情况下经常使用.(然后,我的程序总运行时间的大约30%用于执行rbinds.)
有谁知道更好的解决方案?
Bri*_*ggs 21
还有两个解决方案
第一个是对问题中示例的修改
do.call("rbind", rep(list(A), n))
Run Code Online (Sandbox Code Playgroud)
第二种方法是展开矩阵,复制矩阵并重新组装.
matrix(rep(t(A),n), ncol=ncol(A), byrow=TRUE)
Run Code Online (Sandbox Code Playgroud)
由于效率是要求的,因此必须进行基准测试
library("rbenchmark")
A <- matrix(1:15, nrow=3)
n <- 10
benchmark(rbind(A, A, A, A, A, A, A, A, A, A),
do.call("rbind", replicate(n, A, simplify=FALSE)),
do.call("rbind", rep(list(A), n)),
apply(A, 2, rep, n),
matrix(rep(t(A),n), ncol=ncol(A), byrow=TRUE),
order="relative", replications=100000)
Run Code Online (Sandbox Code Playgroud)
这使:
test replications elapsed
1 rbind(A, A, A, A, A, A, A, A, A, A) 100000 0.91
3 do.call("rbind", rep(list(A), n)) 100000 1.42
5 matrix(rep(t(A), n), ncol = ncol(A), byrow = TRUE) 100000 2.20
2 do.call("rbind", replicate(n, A, simplify = FALSE)) 100000 3.03
4 apply(A, 2, rep, n) 100000 7.75
relative user.self sys.self user.child sys.child
1 1.000 0.91 0 NA NA
3 1.560 1.42 0 NA NA
5 2.418 2.19 0 NA NA
2 3.330 3.03 0 NA NA
4 8.516 7.73 0 NA NA
Run Code Online (Sandbox Code Playgroud)
所以最快的是原始rbind
呼叫,但假定n
是固定的并且提前知道.如果n
不是固定的,那么最快的是do.call("rbind", rep(list(A), n)
.这些是3x5矩阵和10次重复.不同大小的矩阵可能会给出不同的排序.
编辑:
对于n = 600,结果的顺序不同(省略显式rbind
版本):
A <- matrix(1:15, nrow=3)
n <- 600
benchmark(do.call("rbind", replicate(n, A, simplify=FALSE)),
do.call("rbind", rep(list(A), n)),
apply(A, 2, rep, n),
matrix(rep(t(A),n), ncol=ncol(A), byrow=TRUE),
order="relative", replications=10000)
Run Code Online (Sandbox Code Playgroud)
给
test replications elapsed
4 matrix(rep(t(A), n), ncol = ncol(A), byrow = TRUE) 10000 1.74
3 apply(A, 2, rep, n) 10000 2.57
2 do.call("rbind", rep(list(A), n)) 10000 2.79
1 do.call("rbind", replicate(n, A, simplify = FALSE)) 10000 6.68
relative user.self sys.self user.child sys.child
4 1.000 1.75 0 NA NA
3 1.477 2.54 0 NA NA
2 1.603 2.79 0 NA NA
1 3.839 6.65 0 NA NA
Run Code Online (Sandbox Code Playgroud)
如果您包含显式rbind
版本,则它比do.call("rbind", rep(list(A), n))
版本略快,但不会比版本apply
或matrix
版本慢得多.因此n
,在这种情况下,对任意的概括不需要速度损失.