假设我想以并行方式将myfunction
应用于myDataFrame
的每一行。假设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]) }
问题在于,即使我将
COLUMN1_odf
和 COLUMN2_odf
插入到 clusterExport
中,R 仍然无法识别它们。我该如何解决这个问题?是否有一种方法可以“导出”所有 snow 需要的对象,以避免枚举每个对象?编辑1:我已经添加了一条注释(在上面的代码中),以便指定
myfunction
内部创建了 otherDataFrame
。编辑2:为了让
myfunction
更通用,我添加了一些伪代码:现在它使用一个全局数据框 (aGlobalDataFrame
) 和另一个函数 otherFunction
。
myFunction
函数的参数应该包含所有对象。尝试使用myFunction <- function(otherDataFrame, fst, snd) {...
。 - Roman LuštrikparApply
,可以使用parLapply
。do.call(bind_rows,parLapply(clus,1:nrow (myDataFrame),function(i, r) { myfunction(r[i,1],r[i,2]) }
。(我还没有测试过这个。它可能仍然需要一些调整) - Benjamin