tryCatch with a complicated function and plyr in R

时光毁灭记忆、已成空白 提交于 2019-12-06 11:11:24

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"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!