gpt4 book ai didi

r - 并行计算时函数参数中的变量不会传递给集群

转载 作者:行者123 更新时间:2023-12-04 12:06:56 24 4
gpt4 key购买 nike

在与并行包交互时,我很难理解变量是如何限定范围/传递给函数的

library(parallel)

test <- function(a = 1){
no_cores <- detectCores()-1
clust <- makeCluster(no_cores)
result <- parSapply(clust, 1:10, function(x){a + x})
stopCluster(clust)
return(result)
}

test()
[1] 4 5 6 7 8 9 10 11 12 13

x = 1
test(x)

Error in checkForRemoteErrors(val) :
3 nodes produced errors; first error: object 'x' not found

test() 有效,但 test(x) 无效。当我如下修改函数时,它起作用了。

test <- function(a = 1){
no_cores <- detectCores()-1
clust <- makeCluster(no_cores)
y = a
result <- parSapply(clust, 1:10, function(x){y + x})
stopCluster(clust)
return(result)
}

x = 1
test(x)

谁能解释一下内存中发生了什么?

最佳答案

这是由于惰性求值。参数 a 在第一次使用之前不会在函数调用中求值。在第一种情况下,集群不知道 a,因为它尚未在父环境中进行评估。您可以通过强制评估来修复它:

test <- function(a = 1){
no_cores <- detectCores()-1
clust <- makeCluster(no_cores)
force(a) # <------------------------
result <- parSapply(clust, 1:10, function(x){a + x})
stopCluster(clust)
return(result)
}

x = 1
test(x)
# [1] 2 3 4 5 6 7 8 9 10 11

关于r - 并行计算时函数参数中的变量不会传递给集群,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54001775/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com