2013-04-22 53 views
1
命名的所有功能

你好,我現在用的是foreach包的%dopar%並行功能(parallel作爲後端) 我有這樣我能做些什麼,以避免使用的foreach

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

問題一行代碼是getSetOrderData調用不同的函數,這些函數本身調用函數。它看起來像我必須指定所有子功能...

有沒有辦法讓我避免這樣做?

+0

把所有的功能放在一個包裏? – Roland 2013-04-22 09:59:05

+0

:) come'on @Rolland \t這樣做是很多工作,當然有一些簡單的東西比如導出環境或... – statquant 2013-04-22 10:02:53

+0

這些函數在哪裏定義?大概不包,因爲你通過「exportedPkg」處理它們。他們都在'.GlobalEnv',還是在其他地方? – 2013-04-22 16:40:47

回答

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

+0

而不是從任務函數(可能被調用很多次)調用'source',我會用'clusterEvalQ(cl,source(「 〜/ util_funcs.R「))'。它更加高效,並且這些函數可用於任何數量的'foreach'循環。 – 2013-04-23 16:19:31

相關問題