[R] Help with try or tryCatch

Liaw, Andy andy_liaw at merck.com
Tue Nov 1 14:24:32 CET 2005


Just a bit of nitpicking:  I believe the preferred way is to see if the
result of try() _inherits_ the try-error class.  This applies to all S3
classes.  I.e., the relevant line should be something like:

    if (inherits(answer, "try-error")) ...

Andy

> From: David Scott
> 
> On Mon, 31 Oct 2005, McGehee, Robert wrote:
> 
> > 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)
> > }
> >
> 
> This approach worked. I had to define a test function of this 
> sort outside 
> of the loops and then call it within the loops with 
> appropriate parameter 
> values. Thanks for the assistance.
> 
> 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! 
> http://www.R-project.org/posting-guide.html
> 
>




More information about the R-help mailing list