How do I write R code that allows me to execute a different path in my code if an error condition happens? I\'m using a function that tends to throw an error. When it meets
t <- try(pJohnson(.18, parms))
if("try-error" %in% class(t)) alternativeFunction()
Another option might be to use a tryCatch
expression. Here's an example:
vari <- 1
tryCatch(print("passes"), error = function(e) print(vari)) # => passes
tryCatch(stop("fails"), error = function(e) print(vari)) # => 1
You can do whatever you want within the error block, so in your case, something like this should work:
tryCatch(pJohnson(.18, parms), error=function(e) alternativeFunction())
This isn't really the intended usage of the error, but it's a little more concise.