[R] capturing errors in Sweave
Sharpie
chuck at sharpsteen.net
Tue Mar 2 08:42:51 CET 2010
Sundar Dorai-Raj-2 wrote:
>
> Hi,
>
> I'm writing a manual using Sweave and I want to be able to print errors
> from
> bad code. Here's an example:
>
> <Function-4a>>=
> MySqrt <- function(x) {
> if (missing(x)) {
> stop("'x' is missing with no default")
> }
> if (!is.numeric(x)) {
> stop("'x' should only be numeric")
> }
> if (x < 0) {
> stop("'x' should be non-negative")
> }
> return(sqrt(x))
> }
> MySqrt()
> MySqrt("a")
> MySqrt(-2)
> MySqrt(4)
> @
>
> And I would like the output to be:
>
> MySqrt <- function(x) {
> ...
> }
>> MySqrt()
> Error in MySqrt() : 'x' is missing with no default
>> MySqrt("a")
> Error in MySqrt("a") : 'x' should only be numeric
>> MySqrt(-2)
> Error in MySqrt(-2) : 'x' should be non-negative
>> MySqrt(2)
> [1] 1.414214
>
> I.e. I want the Error statements to print in the tex file and not just
> make
> Sweave to bomb.
>
> Thanks,
>
> --sundar
>
You can catch errors in R using the try() function:
foo <- try( log("A"), silent = TRUE )
if( class( foo ) == 'try-error' ){
print( unclass( foo ) )
}
[1] "Error in log(\"A\") : Non-numeric argument to mathematical function\n"
There might be a more clever way to override the default error handling that
would save you from wrapping everything in try()-- but this method should
work.
Hope it helps!
-Charlie
-----
Charlie Sharpsteen
Undergraduate-- Environmental Resources Engineering
Humboldt State University
--
View this message in context: http://n4.nabble.com/capturing-errors-in-Sweave-tp1574642p1574686.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list