【发布时间】:2019-07-07 22:41:02
【问题描述】:
当我设置 .parallel=TRUE 时,我的自定义函数在 ddply() 中无法识别。
我正在尝试使用 ddply 通过自定义函数进行并行计算。实际的代码和数据会相当长而且很大。我发现以下简单的代码足以解释我的问题:
df <- data.frame(val=1:10, ind=c(rep(2, 5), rep(3, 5)))
library(doSNOW)
registerDoSNOW(makeCluster(2, type = "SOCK"))
my_square <-function(x){return(x^2)}
system.time(print(ddply(df, .(ind), function(x) { Sys.sleep(2); sum(x)}, .parallel=FALSE)))
system.time(print(ddply(df, .(ind), function(x) { Sys.sleep(2); sum(x)}, .parallel=TRUE)))
system.time(print(ddply(df, .(ind), function(x) { Sys.sleep(2); my_square(sum(x))}, .parallel=FALSE)))
system.time(print(ddply(df, .(ind), function(x) { Sys.sleep(2); my_square(sum(x))}, .parallel=TRUE)))
前三个 ddply 运行良好。只有最后一行不起作用,我收到以下错误消息:
Error in do.ply(i) :
task 1 failed - "could not find function "my_square""
In addition: Warning messages:
1: <anonymous>: ... may be used in an incorrect context: ‘.fun(piece, ...)’
2: <anonymous>: ... may be used in an incorrect context: ‘.fun(piece, ...)’
Timing stopped at: 0.03 0 2.08
【问题讨论】: