Skip to content
Back to formatted view

Raw Message

Message-ID: <505912F0.4090305@gmail.com>
Date: 2012-09-19T00:33:52Z
From: Duncan Murdoch
Subject: Trap an error from a function
In-Reply-To: <5058D52F020000CB000C9476@med-webappgwia1.medicine.umaryland.edu>

On 12-09-18 8:10 PM, John Sorkin wrote:
> Window 7
> R 2.15
>
> I am writing a simulation which generates sample sized estimates from simulated data. When I run the function shown below,
> power.t.test(delta=14.02528,sd=1.945226,power=0.8,sig.level=0.05)
>
> I get an error message:
>
>> power.t.test(delta=14.02528,sd=1.945226,power=0.8,sig.level=0.05)
> Error in uniroot(function(n) eval(p.body) - power, c(2, 1e+07)) :
>    f() values at end points not of opposite sign
>
> The fact that the function can not return a sample size is OK, however I need to trap the error and set the sample size equal to NA. How do I trap the error so that when the error occurs I can set sample size equal to NA?

You can wrap the call in try().  Then check whether the result inherits 
from try-error, e.g.

res <- try( ... )
if (inherits(res, "try-error")) { do something to handle the error }
else { proceed as you would with no error }

In the example you gave, the problem is that even a sample size of 2 
gives more than 0.8 power.  The function should probably check for that 
case, but it doesn't.

Duncan Murdoch