gpt4 book ai didi

R、dplyr 和雪 : how to parallelize functions which use dplyr

转载 作者:行者123 更新时间:2023-12-01 12:25:35 26 4
gpt4 key购买 nike

假设我想以并行方式申请 myfunctionmyDataFrame 的每一行.假设 otherDataFrame是一个包含两列的数据框:COLUNM1_odfCOLUMN2_odf出于某些原因在 myfunction 中使用.所以我想用 parApply 写一个代码像这样:

clus <- makeCluster(4)
clusterExport(clus, list("myfunction","%>%"))

myfunction <- function(fst, snd) {
#otherFunction and aGlobalDataFrame are defined in the global env
otherFunction(aGlobalDataFrame)

# some code to create otherDataFrame **INTERNALLY** to this function
otherDataFrame %>% filter(COLUMN1_odf==fst & COLUMN2_odf==snd)
return(otherDataFrame)
}
do.call(bind_rows,parApply(clus,myDataFrame,1,function(r) { myfunction(r[1],r[2]) }

这里的问题是 R 无法识别 COLUMN1_odfCOLUMN2_odf即使我将它们插入 clusterExport .我怎么解决这个问题?有没有办法“导出”所有 snow 的对象需要为了不枚举它们中的每一个?

编辑 1:我添加了注释(在上面的代码中)以指定 otherDataFrame 内部创建到 myfunction .

编辑 2:我添加了一些伪代码以概括 myfunction :它现在使用全局数据框( aGlobalDataFrame 和另一个函数 otherFunction )

最佳答案

做了一些实验,所以我解决了我的问题(在本杰明的建议下,并考虑了我添加到问题中的“编辑”):

clus <- makeCluster(4)
clusterEvalQ(clus, {library(dplyr); library(magrittr)})
clusterExport(clus, "myfunction", "otherfunction", aGlobalDataFrame)

myfunction <- function(fst, snd) {
#otherFunction and aGlobalDataFrame are defined in the global env
otherFunction(aGlobalDataFrame)

# some code to create otherDataFrame **INTERNALLY** to this function
otherDataFrame %>% dplyr::filter(COLUMN1_odf==fst & COLUMN2_odf==snd)
return(otherDataFrame)
}

do.call(bind_rows, parApply(clus, myDataFrame, 1,
{function(r) { myfunction(r[1], r[2]) } )

这样我就注册了 aGlobalDataFrame , myfunctionotherfunction ,简而言之,所有用于并行化作业的函数和数据( myfunction 本身)

关于R、dplyr 和雪 : how to parallelize functions which use dplyr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40199284/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com