4

I want to check whether R command has error or not in iflese command. Similar to following one. I wonder how to accomplish this one. Actually I want to run the following code only if there is no error in the previous R code.

ifelse(
      test= Check R Command has error or not
    , yes = FALSE
    , no = TRUE
    )


ifelse(
      test= log("a") # Has error
    , yes = 3
    , no = 1
    )
Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
MYaseen208
  • 22,666
  • 37
  • 165
  • 309

1 Answers1

5

You can use tryCatch for this:

tryCatch({
  log(10)
  1
}, error=function(e) 3)

# [1] 1


tryCatch({
  log('a')
  1
}, error=function(e) 3)

# [1] 3

In the second example above, the first expression (which can be multi-line, as above) throws an error, so the expression passed to the error argument is executed.

jbaums
  • 27,115
  • 5
  • 79
  • 119