1

您好我正在使用包的%dopar%并行功能foreachparallel作为后端)我有一行这样的代码

exportedFn <- #STUFF
exportedPkg <- #STUFF
allDataT <- foreach(myFile=orderFiles, .combine='rbind', .packages=exportedPkg, .export=exportedFn) %dopar% getSetOrderData(myFile, f.type="SUBMIT");

问题是getSetOrderData调用不同的函数,这些函数本身调用函数。看来我必须指定所有子功能...

有没有办法让我避免这样做?

4

1 回答 1

3

确保所有变量都在相同的环境中定义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在我的主目录中创建了一个名为的脚本并将这两个函数粘贴到其中,但调用它们fsub2fmain2. 如果我通过以下方式调用它:

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()吗?

于 2013-04-22T10:35:27.180 回答