且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

R:foreach 循环如何找到应该调用的函数?

更新时间:2022-06-23 00:38:03

它们的行为不同,因为 registerDoParallel 在 Linux 上注册了一个 mclapply 后端,而它注册了一个 Windows 上的 clusterApplyLB 后端.使用 mclapply 后端时,基本上没有数据导出问题,因此它适用于 Linux.但是对于 clusterApplyLB,如果 foreach 没有自动导出所需的函数和数据,您可能会遇到问题.

They behave differently because registerDoParallel registers an mclapply backend on Linux, while it registers a clusterApplyLB backend on Windows. When using an mclapply backend, there are essentially no data exporting issues, so it works on Linux. But with clusterApplyLB, you can run into problems if foreach doesn't auto-export the functions and data that are needed.

您可以通过修改FUN3通过.export选项导出FUN来解决这个问题:

You can solve this problem by modifying FUN3 to export FUN via the .export option:

FUN3 <- function(a, b) {
  foreach(i=1:3, .export='FUN') %dopar% FUN(i, a, b)
}

此解决方案适用于 Linux 和 Windows,因为 .exportmclapply 后端忽略.

This solution works on both Linux and Windows, since .export is ignored by the mclapply backend.

正如 Hong Ooi 所指出的,您在使用 clusterExport 时出错,但我不会使用 clusterExport 来解决问题,因为它是后端特定的.

As pointed out by Hong Ooi, you have an error in your use of clusterExport, but I wouldn't use clusterExport to solve the problem since it is backend specific.