将R Apply语句转换为lApply以进行并行处理 [英] Convert R apply statement to lapply for parallel processing

查看:0
本文介绍了将R Apply语句转换为lApply以进行并行处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下R"Apply"语句:

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)
}

因此,我有以下数据结构:

SIMULATION_RESULTS:具有列名的矩阵,用于标识2000个模拟(行)的每条可能的所需模拟查找数据。

除其他项外,

dataframe_stuff_that_needs_lookup_from_simulation:还包含其值与SIMULATION_RESULTS数据结构中的列名匹配的字段。

Matrix_of_sum:运行函数时,用于保存模拟结果的2000行x 250,000列(模拟数量x正在模拟的项目)结构。

因此,Apply函数查找250,000个数据集中每一行的数据帧列值,计算和,并将其存储在Matrix_of_sum数据结构中。

遗憾的是,此处理需要很长时间。我已经探索了使用rowsum作为替代方案,它已经将处理时间减少了一半,但我想尝试多核处理,看看这是否会进一步减少处理时间。有人能帮我把上面的代码从"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)

您也可以尝试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)

我不太确定您希望以什么方式结束输出,但看起来您正在对每个结果进行cbind。但是,如果您期待的是其他内容,请通知我。

这篇关于将R Apply语句转换为lApply以进行并行处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆