2013-04-23 48 views
1

我正在使用包parallel來執行計算。這裏是一個玩具例子:並行計算的stdout和stderr在R

library(parallel) 
m = matrix(c(1,1,1,1,0.2,0.2,0.2,0.2), nrow=2) 
myFun = function(x) { 
    if (any(x<0.5)) { 
    write("less than 0.5", stderr()) 
    return(NA) 
    } else { 
    write("good", stdout()) 
    return(mean(x)) 
    } 
} 
cl = makeCluster(2, outfile="/tmp/output") 
parApply(cl, m, 2, myFun) 
stopCluster(cl) 

的問題是兩個標準輸出和標準錯誤將被重定向到/tmp/output。該output文件看起來像這樣:

starting worker pid=51083 on localhost:11953 at 11:37:12.966 
starting worker pid=51093 on localhost:11953 at 11:37:13.261 
good 
good 
less than 0.5 
less than 0.5 

有什麼辦法分別爲標準輸出和標準錯誤,安裝兩個單獨的文件?以及如何忽略「起始工人pid = ...」的前兩行?

回答

2

parallel包不支持直接發送輸出和錯誤,以單獨的文件,但你可以自己做:

cl = makeCluster(2) 

setup = function(outfile, errfile) { 
    assign("outcon", file(outfile, open="a"), pos=.GlobalEnv) 
    assign("errcon", file(errfile, open="a"), pos=.GlobalEnv) 
    sink(outcon) 
    sink(errcon, type="message") 
} 

shutdown = function() { 
    sink(NULL) 
    sink(NULL, type="message") 
    close(outcon) 
    close(errcon) 
    rm(outcon, errcon, pos=.GlobalEnv) 
} 

clusterCall(cl, setup, "/tmp/output", "/tmp/errmsg") 
parApply(cl, m, 2, myFun) 
clusterCall(cl, shutdown) 

自「首發工人」的消息setup之前發出被調用時,這些消息被重定向到「/ dev/null」,這是未指定outfile時的默認行爲。