Skip to content
Back to formatted view

Raw Message

Message-ID: <CAJ55+dLXk+NAGQSOx2ZyVZW-2_P6pZk1PcrDBNjxX0f4bCV2=g@mail.gmail.com>
Date: 2012-09-19T01:19:18Z
From: Thomas Lumley
Subject: Trap an error from a function
In-Reply-To: <9E42CAF3-4172-46CA-8376-94F60C09B7AE@comcast.net>

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