4

假设我想以并行方式myfunctionmyDataFrame. 假设这otherDataFrame是一个具有两列的数据框:COLUNM1_odf并且COLUMN2_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

4

2 回答 2

5

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

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

通过这种方式,我注册了aGlobalDataFramemyfunction并且,简而言之,用于并行化作业(本身)otherfunction的所有函数和函数使用的数据myfunction

于 2016-10-28T18:56:33.133 回答
0

现在我没有在手机上看这个,我可以看到几个问题。

首先,您实际上并没有otherDataFrame在函数中创建。您正在尝试将现有的管道传输otherDataFramefilter中,如果otherDataFrame环境中不存在,则该功能将失败。

其次,除非您已经将dplyr包加载到集群环境中,否则您将调用错误的filter函数。

最后,当您调用 时parApply,您没有在任何地方指定应该是什么fstsnd应该是什么。尝试以下方法:

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

myfunction <- function(otherDataFrame, fst, snd) {
 dplyr::filter(otherDataFrame, COLUMN1_odf==fst & COLUMN2_odf==snd)
}
do.call(bind_rows,parApply(clus,myDataFrame,1,function(r, fst, snd) { myfunction(r[fst],r[snd]), "[fst]", "[snd]") }
于 2016-10-24T10:25:05.133 回答