我正在尝试加快工作流程,该工作流程涉及通过自定义功能将两个数据帧中的行相乘。
现在,我正在将apply()与自定义函数一起使用。我的理解是lapply()或sapply()会更快(并最终允许并行化,尽管我更喜欢不依赖于并行处理的加速),但我无法弄清楚lapply()或sapply( )语法,我应该在自定义函数中使用。如果有一种更简单的方法来矢量化自定义函数并完全避免使用* apply(),那将是首选。
在我的用例中,行数将为一百万或更多,并且列数将为约15,但是这里有一个MWE说明了速度问题:
# Two data frames that will be used in the calculation. d2 can be a matrix, but d1 must be a data frame.
d1 <- data.frame(V1 = runif(1000), V2 = runif(1000), V3 = runif(1000), V4 = runif(1000))
d2 <- data.frame(Va = runif(3), V1 = runif(3), V2 = runif(3), V3 = runif(3), V4 = runif(3))
# Custom function that is applied to each row in d1
manualprob <- function(x){
xb1 <- as.numeric(rowSums(d2[1,2:ncol(d2)] * x) + d2[1,1])
xb2 <- as.numeric(rowSums(d2[2,2:ncol(d2)] * x) + d2[2,1])
xb3 <- as.numeric(rowSums(d2[3,2:ncol(d2)] * x) + d2[3,1])
denom <- 1 + exp(xb1) + exp(xb2) + exp(xb3)
prob <- exp(xb1)/denom
return(prob)
}
# apply() used below, but it is too slow
start_time <- proc.time()
d1$prob <- as.vector(apply(d1, 1, manualprob))
proc.time() - start_time
user system elapsed
1.081 0.007 1.088
您最好的选择是转换为矩阵并使用R的非常快的矩阵运算...
您可以一次性创建所有xb图形
xb <- as.matrix(d2[, -1]) %*% t(as.matrix(d1)) + d2[, 1]
这将产生3 * 1000的矩阵。
然后您可以通过]获得概率>
prob <- exp(xb[1, ]) / (1 + colSums(exp(xb)))
这一切在我的机器上几乎需要零时间!
如果我们复制行,则可以向量化