[R] How to say "if error"

Duncan Murdoch murdoch.duncan at gmail.com
Thu Jun 24 15:34:52 CEST 2010


On 24/06/2010 7:06 AM, Paul Chatfield wrote:
> I've had a look at the conditions in base and I can't get the ones to work
> I've looked at but it is all new to me.  
>
> For example, I can work the examples for tryCatch, but it won't print a
> finally message for me when I apply it to my model.  Even if I could get
> this to work, I think it would still cause a break e.g.
> for (j in 1:10)
> {tryCatch(ifelse(j==5, stop(j), j), finally=print("oh dear"))}
>
> Thanks for the suggestion though - any others?
>   
I think you don't want to use finally, which is just code that's 
guaranteed to be executed at the end.  You want to catch the errors and 
continue.  For example,

for (j in 1:10)
{ tryCatch(ifelse(j==5, stop(j), print(j)), error=function(e) 
{print("caught error"); print(e)}) }

Duncan Murdoch



More information about the R-help mailing list