Mat*_*a C 4 parallel-processing r lapply
我有以下 R“应用”语句:
for(i in 1:NROW(dataframe_stuff_that_needs_lookup_from_simulation))
{
matrix_of_sums[,i]<-
apply(simulation_results[,colnames(simulation_results) %in%
dataframe_stuff_that_needs_lookup_from_simulation[i,]],1,sum)
}
Run Code Online (Sandbox Code Playgroud)
所以,我有以下数据结构:
simulation_results:具有列名称的矩阵,用于标识 2000 个模拟(行)的每个可能的所需模拟查找数据。
dataframe_stuff_that_needs_lookup_from_simulation:除其他项外,还包含其值与simulation_results数据结构中的列名称匹配的字段。
matrix_of_sums:运行函数时,一个 2000 行 x 250,000 列(模拟数量 x 正在模拟的项目)结构用于保存模拟结果。
因此,apply 函数正在查找 250,000 个数据集中每行的数据帧列值,计算总和,并将其存储在matrix_of_sums 数据结构中。
不幸的是,这个处理需要很长时间。我已经探索了使用 rowsums 作为替代方案,它已将处理时间减少了一半,但我想尝试多核处理,看看这是否会进一步减少处理时间。有人可以帮我将上面的代码从“apply”转换为“lapply”吗?
谢谢!
与基本 R 平行,尝试
library(parallel)
cl <- makeCluster(detectCores())
matrix_of_sums <- parLapply(cl, 1:nrow(dataframe_stuff_that_needs_lookup_from_simulation), function(i)
rowSums(simulation_results[,colnames(simulation_results) %in%
dataframe_stuff_that_needs_lookup_from_simulation[i,]]))
stopCluster(cl)
ans <- Reduce("cbind", matrix_of_sums)
Run Code Online (Sandbox Code Playgroud)
你也可以尝试foreach %dopar%
library(doParallel) # will load parallel, foreach, and iterators
cl <- makeCluster(detectCores())
registerDoParallel(cl)
matrix_of_sums <- foreach(i = 1:NROW(dataframe_stuff_that_needs_lookup_from_simulation)) %dopar% {
rowSums(simulation_results[,colnames(simulation_results) %in%
dataframe_stuff_that_needs_lookup_from_simulation[i,]])
}
stopCluster(cl)
ans <- Reduce("cbind", matrix_of_sums)
Run Code Online (Sandbox Code Playgroud)
我不太确定你最后想要的输出如何,但看起来你正在对cbind每个结果进行处理。如果您还期待其他内容,请告诉我。