[R] Help with try or tryCatch

McGehee, Robert
Mon, 31 Oct 2005 21:32:35 -0000

It sounds like you want `try` with the argument `silent = TRUE`. This
will allow you to keep running your program without errors. If you want
to check if the line had an error, you can error control by seeing if
the class of the resulting object is "try-error". For example,
let's say
I wanted to make an error-proof `plus` function, such that trying "a"
+
2 would result in NA instead of an error.

newPlus <- function(x, y) {
	answer <- try(x + y, silent = TRUE)
	if (class(answer) == "try-error") return(NA) else return(answer)
}

> newPlus(1, 2)
[1] 3
> newPlus("a", 2)
[1] NA

tryCatch is generally useful when one wants to run a script that may
contain errors, and regardless of whether errors are encountered
tryCatch will run a `finally` script after the main script completes.
This is extremely helpful, for instance, if your primary script creates
some auxiliary connections or temporary files that you want to clean
up/delete after the main script finishes, whether there was an error or
not.

Hope this helps,
Robert

-----Original Message-----
From: David Scott [mailto:d.scott at auckland.ac.nz]
Sent: Monday, October 31, 2005 3:56 PM
To: r-help at stat.math.ethz.ch
Subject: [R] Help with try or tryCatch



I am having trouble with try and tryCatch.

I have read the documentation but I just don't get it.

Here is what I am trying to do. I am testing a function which has a
number
of parameters. I want to test it for different values of the parameters
and I have some loops, in the middle of which is a test of the function.

Sometimes the routine fails and so I have put the bit that might fail
inside try(). I would like to keep running through the loops when that
happens, but the whole computation stops. I have read in the
documentation
about restarts and seen that there is a pre-established restart which
jumps to the top level, and I am guessing that that is what is
happening.
What I can't see is how to get the computation to restart from the error

and just continue through the loop.

Any suggestions or pointers would be most welcome.

David Scott

_________________________________________________________________
David Scott	Department of Statistics, Tamaki Campus
 		The University of Auckland, PB 92019
 		Auckland	NEW ZEALAND
Phone: +64 9 373 7599 ext 86830		Fax: +64 9 373 7000
Email:	d.scott at auckland.ac.nz


Graduate Officer, Department of Statistics

______________________________________________
R-help at stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide!