節點的對象這是我覺得很難理解的東西:如何提供給在雪地裏包的R並行計算
cl = makeCluster(rep("localhost", 8), "SOCK")
# This will not work, error: dat not found in the nodes
pmult = function(cl, a, x)
{
mult = function(s) s*x
parLapply(cl, a, mult)
}
scalars = 1:4
dat = rnorm(4)
pmult(cl, scalars, dat)
# This will work
pmult = function(cl, a, x)
{
x
mult = function(s) s*x
parLapply(cl, a, mult)
}
scalars = 1:4
dat = rnorm(4)
pmult(cl, scalars, dat)
# This will work
pmult = function(cl, a, x)
{
mult = function(s, x) s*x
parLapply(cl, a, mult, x)
}
scalars = 1:4
dat = rnorm(4)
pmult(cl, scalars, dat)
第一個功能不因參數懶評價工作。但什麼是懶惰評價?當mult()被執行時,它不需要x被評估嗎?第二個是有效的,因爲它迫使x被評估。現在最奇怪的事情發生在第三個函數中,沒有做任何事情,但使mult()接收x作爲額外的參數,並突然一切正常!
另一件事是,如果我不想在調用parLapply()的函數內部定義所有的變量和函數,該怎麼辦?以下是絕對不會工作:
pmult = function(cl)
{
source("a_x_mult.r")
parLapply(cl, a, mult, x)
}
scalars = 1:4
dat = rnorm(4)
pmult(cl, scalars, dat)
我可以通過這些變量和函數作爲參數:
f1 = function(i)
{
return(rnorm(i))
}
f2 = function(y)
{
return(f1(y)^2)
}
f3 = function(v)
{
return(v- floor(v) + 100)
}
test = function(cl, f1, f2, f3)
{
x = f2(15)
parLapply(cl, x, f3)
}
test(cl, f1, f2, f3)
或者,我可以用clusterExport(),但是當有很多,它會很麻煩要導出的對象。有沒有更好的辦法?
見'force'? –