Reputation: 13524
Is there a function in R that returns "FALSE" if an error is given, otherwise returns "TRUE"? Or something along these lines, or do I need to create my own by evaluating something like ifelse(class(try(stop())) == "try-error", FALSE, TRUE)
?
Upvotes: 3
Views: 5475
Reputation: 70623
I had to do this on occasion or two. What I did is I used tryCatch
along these lines. This can be handy if you're doing simulations and sometimes some algorithm doesn't converge and produces a warning, but you want to ignore it, because you don't want your simulation to die while running on 100 nodes on a super computer.
> out <- tryCatch(stop("bla"), error = function(e) e)
> any(class(out) == "error")
[1] TRUE
If process goes through uninterrupted (without error), you get FALSE.
> out <- tryCatch(1:5, error = function(e) e)
> out
[1] 1 2 3 4 5
> any(class(out) == "error")
[1] FALSE
Upvotes: 9
Reputation: 263311
You surely would not want to use ifelse
but perhaps this will show a more effective route:
> if( inherits(res <- try( stop() ), "try-error") ){ FALSE} else{ res}
Error in try(stop()) :
[1] FALSE
> if( inherits( res <- try( "ppp" ), "try-error") ){ FALSE} else{ res}
[1] "ppp"
Now that I think about it a bit: The answer is just inherits(tryres, "try-error")
since that does return a logical. How you decide to process it is then up to you. It is true that many times testing class(tryres)=="tryerror
will succeed but sometimes there is more than one class returned, in which case it will not.
Upvotes: 4