R parSapply 无法识别该功能

R parSapply does not recognize the function

我想使用 parSapply 并行化用户函数。我遵循了一些教程,并在下面的代码中找到了它。但是parSapply函数returns报错:

library(parallel)

dummy_function <- function(x,y){
  x_ <- runif(1000, 0, x)
  y_ <- runif(1000, 0, y)
  return(median(x_*y_))
}

#it works with replicate
replicate(1000, dummy_function(2,5))


cl <- makeCluster(detectCores()-1)
clusterEvalQ(cl,library(MASS))
clusterSetRNGStream(cl)
clusterExport(cl, c("dummy_function"))

#it does not work with parSappply
results <- parSapply(cl, 1:1000, dummy_function(2,5))

# Error in match.fun(FUN) : 
#   'dummy_function(2, 5)' is not a function, character or symbol

stopCluster(cl)

谢谢!

创建 lambda 函数

results <- parSapply(cl, 1:1000, function(u) dummy_function(x = 2, y = 5))

-正在检查

> length(results)
[1] 1000

您的问题:正确的语法是 sapply(vec, fun) 而不是 sapply(vec, fun(arg1, arg2).

因此,根据您的设置,我会将 25 作为 dummy_function:

参数的默认值
dummy_function <- function(x=2, y=5) { # <-- changes made here
    x_ <- runif(1000, 0, x)
    y_ <- runif(1000, 0, y)
    return(median(x_*y_))
}

然后你可以 运行 replicate 不传递参数:

replicate(1000, dummy_function())

然后你 运行 parSapply(同样没有参数):

results <- parSapply(cl, 1:1000, dummy_function)