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
  • 24,988
  • 16
  • 102
  • 110
MYaseen208
  • 21,368
  • 34
  • 145
  • 286

1 Answers1

4

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
  • 26,405
  • 5
  • 76
  • 118