2013-02-25 43 views
2

我有一个复杂的,我用来做模拟的长函数。它可能会产生错误,主要是随机向量与零方差结果相等的值,从而导致PCA或逻辑回归。tryCatch具有复杂的功能和plyr在R

我正在群集上使用doMCplyr执行它。我不希望tryCatch函数中的每一件小事情,因为错误的可能性很多,并且它们中的每一个的概率都很小。

我该如何尝试抓住每一次运行,而不是tryCatch ing每一个小行?该代码是这样的:

iteration = function(){ 
    a really long simulation function where errors can happen 
    } 
reps = 10000 
results = llply(1:reps, function(idx){out<-iteration()},.parallel=TRUE) 

编辑约一年后:foreach封装使该大致比它更容易与plyr

library(foreach) 
output <- foreach(i=1:reps, .errorhandling = 'remove')%dopar%{ 
    function 
} 

回答

2

你可以用的尝试捕捉环路你传递给llply的函数?

results = llply(1:reps, function(idx){ 
    out = NA 
    try({ 
     out<-iteration() 
    }, silent=T) 
    out 
},.parallel=TRUE) 
0

你可以把tryCatch在你的功能迭代,例如:

iteration <- function(idx){ 
    tryCatch(
    { idx <- idx+1 
     ## very long treatments here... 
     ## I add a dummy error here to test my tryCatch 
     if(idx %% 2000 ==0) stop("too many iterations") 
    },error = function(e) print(paste('error',idx))) 
} 

现在内llply测试它,

library(plyr) 
reps = 10000 
results = llply(1:reps, iteration,.parallel=TRUE) 
1] "error 2000" 
[1] "error 4000" 
[1] "error 6000" 
[1] "error 8000" 
[1] "error 10000"