我需要选择矩阵行的最大元素,但是将我的自我限制在某些列之间的间隔。我需要多次这样做,并且#34;列范围"我每次都需要改变一下。到目前为止,这是绑定约束,阻止我在合理的时间内运行模拟。以下是我正在做的事情的一个例子。我需要优化的代码是mapply(function(x,y) apply(A[c(x,x:y,y),],2,max),Min,Max)
A=matrix(runif(100^2),ncol=100)
Min=sample(80,10000,replace=T)
Max=Min+sample(1:10,10000,replace=T)
system.time(mapply(function(x,y) apply(A[c(x,x:y,y),],2,max),Min,Max))
user system elapsed
1.52 0.01 1.54
答案 0 :(得分:2)
以下是使用matrixStats
库的示例。请注意,我已经回答了你的问题。您提供的代码与您的问题“不一致”。请参阅我的评论。
library(matrixStats)
myA <- mapply(function(x,y) rowMaxs(A, cols = x:y), Min, Max)
为了更有效地为您的代码计时,我做了以下调整:
library(matrixStats)
n = 1e3
dim = 1e3
A = matrix(sample(100, dim*dim, replace = T), nrow = dim, ncol = dim)
Min = sample(dim*.8, n, replace = T)
Max = Min + sample(1:10, n, replace = T)
f1 <- function(){
mapply(function(x,y) rowMaxs(A, cols = x:y), Min, Max)
}
f2 <- function(){
mapply(function(x,y) apply(A[, c(x:y)], 1, max), Min ,Max)
}
当我采用rowMaxs
方式时,它比apply
方法快37倍
microbenchmark(f1(), f2(), times = 10)
Unit: milliseconds
expr min lq mean median uq max neval
f1() 76.20204 77.89764 98.98646 93.06952 107.3973 159.0868 10
f2() 2806.49448 3340.67081 3652.18062 3417.00287 3637.7743 5130.4474 10