tryCatch with a complicated function and plyr in R

2019-05-25 07:48发布

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
}

2条回答
可以哭但决不认输i
2楼-- · 2019-05-25 08:04

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"
查看更多
我想做一个坏孩纸
3楼-- · 2019-05-25 08:18

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)
查看更多
登录 后发表回答