确保所有变量都在相同的环境中定义getSetOrderData
?我发现如果我定义
fsub <- function( x ){
return( x^2 )
}
fmain <- function( x ){
x <- fsub( x ) + 2
return(x)
}
然后我这样使用它们:
require(doParallel)
cl <- makeCluster( 2 , outfile = "" )
registerDoParallel( cl )
foreach( k = 1:2 , .verbose = TRUE , .combine = c ) %dopar%{
fmain( k )
}
我得到了预期的结果:
numValues: 2, numResults: 0, stopped: TRUE
automatically exporting the following variables from the local environment:
fmain, fsub
got results for task 1
numValues: 2, numResults: 1, stopped: TRUE
returning status FALSE
got results for task 2
numValues: 2, numResults: 2, stopped: TRUE
first call to combine function
evaluating call object to combine results:
fun(result.1, result.2)
returning status TRUE
[1] 3 6
此外,如果我.GlobalEnv
在另一个函数内部调用函数(未在其中定义的函数),使用source()
它仍然可以工作。假设我util_funcs.R
在我的主目录中创建了一个名为的脚本并将这两个函数粘贴到其中,但调用它们fsub2
和fmain2
. 如果我通过以下方式调用它:
fsource <- function( x ){
source( "~/util_funcs.R" )
x <- fmain2( x )
return( x )
}
它仍然有效:
numValues: 2, numResults: 0, stopped: TRUE
automatically exporting the following variables from the local environment:
fsource
got results for task 1
numValues: 2, numResults: 1, stopped: TRUE
returning status FALSE
got results for task 2
numValues: 2, numResults: 2, stopped: TRUE
first call to combine function
evaluating call object to combine results:
fun(result.1, result.2)
returning status TRUE
[1] 3 6
您可以在一个简单的 R 脚本中复制/粘贴所有功能并使用source()
吗?