[R] Help with tryCatch

William Dunlap wdunlap at tibco.com
Sun Jul 10 20:51:23 CEST 2011


Don't bother putting the 'zest[i]<-' into the error handler: the
retun value of the handler will be the return value of tryCatch:

E.g.,
  > tryCatch(stop("Oops"), error=function(cond)NA,
warning=function(cond)-1)
  [1] NA
  > tryCatch(warning("Hmm"), error=function(cond)NA,
warning=function(cond)-1)
  [1] -1
  > tryCatch(log(10), error=function(cond)NA, warning=function(cond)-1)
  [1] 2.302585

Usually people put the call to tryCatch inside the call to sapply
so you can recover from errors in any iteration of the loop in
sapply.
  > sapply(1:5,
           FUN=function(i) {
              tryCatch(
                 if(i%%2==0) {
                    stop("i is even")
                 } else {
                    (i-1)/2
                 },
              error=function(cond)NA)
           })
   [1]  0 NA  1 NA  2
but you may have good reason to want to return a single NA if any
iteration of sapply causes an error.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com  

> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of eric
> Sent: Sunday, July 10, 2011 9:25 AM
> To: r-help at r-project.org
> Subject: [R] Help with tryCatch
> 
> Having a hard time understanding the help files for tryCatch. 
> Looking for a
> little help with the following statement which sits inside a for loop
> 
> zest[i] <- tryCatch(sapply(getNodeSet(zdoc, "//zestimate/amount"),
> xmlValue), error=function() zest[i] <-"NA")
> 
> zest is a numeric vector
> 
> If the sapply statement evaluates to an error, I'd like to 
> set the value of
> zest[i] to NA and continue with the loop.
> 
> Suggestions ?
> 
> --
> View this message in context: 
> http://r.789695.n4.nabble.com/Help-with-tryCatch-tp3657859p365
7859.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 



More information about the R-help mailing list