[R] Automatic re-looping after error

Martin Maechler maechler at stat.math.ethz.ch
Mon Oct 13 11:14:40 CEST 2003


>>>>> "Ted" == Ted Harding <Ted.Harding at nessie.mcc.ac.uk>
>>>>>     on Sun, 12 Oct 2003 13:44:27 +0100 (BST) writes:

 <.....>

    Ted> I've now installed R-1.8.0 which does include
    Ted> 'tryCatch' and related things, but from the look of it
    Ted> I'll have to study it a bit before I see how it all
    Ted> works!

    Ted> Meanwhile, thanks to others (Spencer Graves, Achim
    Ted> Zeileis, as well as Thomas Lumley and Andy Liaw) for
    Ted> suggestions. Though I'd already looked at "try", I
    Ted> thought I'd have another go. It turns out I'd been
    Ted> muddled about testing the result of 'try' in the right
    Ted> way.

    Ted> In fact, if 'myfun(...)' might fail in a loop, then

    Ted>   result <- try(myfun(...));
    Ted>   if(class(result)=="try-error") next ;

    Ted> will have the effect of breaking out of the current
    Ted> cycle of the loop and starting a new cycle. Otherwise
    Ted> 'result' will be a valid returned value from
    Ted> 'myfun'. This is exactly what I had wanted.

very good.

slightly more recommendable code is

   result <- try(myfun(...))
   if(inherits(result, "try-error")) next 


- using  inherits(obj, cls) is more robust than 
  class(obj) == cls because it also works when  `obj' has more
  than one class (e.g. a `glm' object) or when `obj' has no
  class {i.e. when `methods' is not attached or in older R versions}.

- no trailing ";"

Martin Maechler <maechler at stat.math.ethz.ch>	http://stat.ethz.ch/~maechler/
Seminar fuer Statistik, ETH-Zentrum  LEO C16	Leonhardstr. 27
ETH (Federal Inst. Technology)	8092 Zurich	SWITZERLAND
phone: x-41-1-632-3408		fax: ...-1228			<><




More information about the R-help mailing list