catching an error and then branching logic

后端 未结 2 437
借酒劲吻你
借酒劲吻你 2020-12-02 12:16

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

相关标签:
2条回答
  • 2020-12-02 12:45
    t <- try(pJohnson(.18, parms))
    if("try-error" %in% class(t)) alternativeFunction()
    
    0 讨论(0)
  • 2020-12-02 12:57

    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.

    0 讨论(0)
提交回复
热议问题