Skip to content

question about TryCatch and lapply

4 messages · John Kerpel, jim holtman, Martin Morgan

#
Please show us the 'lapply' statement you are using.  Here is a simple
case of catching an error in an lapply and continuing:
+     a <- try(stopifnot(x > 0))  # force an error
+     if (inherits(a, 'try-error')) return(NULL)
+     x
+ })
Error : x > 0 is not TRUE
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
NULL

[[4]]
[1] 4

        
On Fri, May 25, 2012 at 2:51 PM, John Kerpel <john.kerpel at gmail.com> wrote:

  
    
#
On 5/25/2012 12:48 PM, John Kerpel wrote:
In the context of tryCatch in your question

   lst <- list(1, 2, -3, 4)
   sapply(lst, function(x) tryCatch({
       stopifnot(x > 0)
       x
   }, error=function(err) {
       NA
   }))

which separates out the implementation of the function from the error 
handling instead of intermingling the two as with try(). Or a little 
more elaboration, reporting the error to stderr as might be appropriate 
for a parallel job

   sapply(lst, function(x) {
       tryCatch({
           stopifnot(x>0)
           sqrt(x)
       }, error=function(err) {
           ## demote to message on stderr; in context of tryCatch so
           ## 'x' visible
           message(conditionMessage(err), "; x = ", x)
           NaN
       })
   })

or for warnings, showing use of restarts

   withCallingHandlers({
       sapply(lst, sqrt)
   }, warning=function(warn) {
       message(conditionMessage(warn))
       ## restart where the warning occurs; see ?warning and source for
       ## warning()
       invokeRestart("muffleWarning")
   })

Martin