tryCatch with a complicated function and plyr in R
Asked Answered
A

2

2

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 tryCatching 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
}
Aide answered 25/2, 2013 at 19:43 Comment(0)
D
2

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)
Defeat answered 25/2, 2013 at 20:0 Comment(0)
N
0

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"
Nozicka answered 25/2, 2013 at 20:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.