sparkh2o
sparkh2o

Reputation: 264

Check for errors in R

How would I check and catch error in R, for example, log("a") produces "Error in log("a") : non-numeric argument to mathematical function" error. Is there a way, I can perform the following style code to check that if this error is produced, return a statement? I realize that tryCatch blocks can be used but am not sure how to use them to check for a specific error message.

if (log("a") == "Error in log("a") : non-numeric argument to mathematical function")
{
  print("error returned")
}

Upvotes: 1

Views: 2139

Answers (1)

IRTFM
IRTFM

Reputation: 263481

The type of error is in an attribute. I'm showing how to check the $message element of that list. The value of try() will either be the value of the expression or "try-error":

res <- try(log("a"), TRUE)
str(res)
#-----
Class 'try-error'  atomic [1:1] Error in log("a") : non-numeric argument to mathematical function

  ..- attr(*, "condition")=List of 2
  .. ..$ message: chr "non-numeric argument to mathematical function"
  .. ..$ call   : language log("a")
  .. ..- attr(*, "class")= chr [1:3] "simpleError" "error" "condition"
#------------

 if( grep("non-numeric", attr(res,"condition")$message ) ) {print("argument not a number")}
#[1] "argument not a number"

Upvotes: 2

Related Questions