I've got a complicated, long function that I'm using to do simulations. It can generate errors, mostly having to do with random vectors ending up with equal values with zero-variance, getting fed either into PCA's or logistic regressions.
I'm executing it on a cluster using doMC
and plyr
. I don't want to tryCatch
every little thing inside of the function, because the possibilities for errors are many and the probabilities of each of them are small.
How do I tryCatch each run, rather than tryCatch
ing every little line?? The code is something like this:
iteration = function(){
a really long simulation function where errors can happen
}
reps = 10000
results = llply(1:reps, function(idx){out<-iteration()},.parallel=TRUE)
EDIT about a year later:
The foreach
package makes this substantially easier than it is with plyr
library(foreach)
output <- foreach(i=1:reps, .errorhandling = 'remove')%dopar%{
function
}
Can you wrap the try catch loop in the function you pass to llply?
results = llply(1:reps, function(idx){
out = NA
try({
out<-iteration()
}, silent=T)
out
},.parallel=TRUE)
You can put tryCatch
within you function iteration, For example:
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)))
}
Now testing it within 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"
来源:https://stackoverflow.com/questions/15075113/trycatch-with-a-complicated-function-and-plyr-in-r