[R] Trap an error from a function

Thomas Lumley tlumley at uw.edu
Wed Sep 19 03:19:18 CEST 2012


On Wed, Sep 19, 2012 at 12:56 PM, David Winsemius
<dwinsemius at comcast.net> wrote:
> Basically you run you each iteration of your code inside try() and then test to see if it's class vector includes "try-error", ... then you can do something with the result or return NA. This may makeit more useful because I return the results at each iteration if there was no error:
>
> sapply(test, function(x)  if( "try-error" %in% class(try( Z <- exp(test[test[x:1]] ) ) ) ){NA}else{Z} )
>
>

I think it's easier to use tryCatch(), eg


sample.size <- tryCatch(

power.t.test(delta=14.02528,sd=1.945226,power=0.8,sig.level=0.05)$n,
                 error=function(e) NA
                 )

The first line gets run, and if there's an error, the error is passed
to the error= argument.  This is a function that takes the error as an
argument, and could do sophisticated things with it, but actually just
returns NA for all errors.

tryCatch() is also quieter.

  -thomas

-- 
Thomas Lumley
Professor of Biostatistics
University of Auckland




More information about the R-help mailing list