2

This workflow will either produce a value or an error. I want that, in the event of an error, will perform an arbitrary code (it could print a message to the console, create an objet).

a <- 1
b <- 2
e <- 3

Using the function from How can I use an error as an if statement in R

is_simple_error <- function(x) inherits(x, "simpleError")

This will evaluate to the desired printed message:

 if (is_simple_error(a + b) == TRUE) {
   stop("Check the inputs")
        } else {
          print("You can continue with the script")
        }

But in the event of an error, the desired output ("Check the inputs") will not be printed to the terminal. Instead, we have an error: "Error: object 'd' not found"):

if (is_simple_error(e + d) == TRUE) {
  stop("Check the inputs")
} else {
  print("You can continue the script")
3
  • Just to drive out confounds on 'error', perhaps rename c away from a function name to stick with remarking on other errors.
    – Chris
    Commented Jul 4 at 18:49
  • Thank you, fixed it, renamed the object to "e". "c" is a bad name for an object in R.
    – BMLopes
    Commented Jul 4 at 18:58
  • stackoverflow.com/questions/64688082/…
    – M--
    Commented Jul 5 at 0:43

2 Answers 2

1

You need to actually catch the error, otherwise the process gets interrupted at the moment the error is generated:

is_simple_error <- function(expr) {
  result <- tryCatch(expr, error = function(e) e) 
  inherits(result, "simpleError")
}

Then it works:

if (is_simple_error(a + b)) {
  stop("Check the inputs")
} else {
  print("You can continue with the script")
}
[1] "You can continue with the script"
if (is_simple_error(e + d)) {
  stop("Check the inputs")
} else {
  print("You can continue the script")
}
Error: Check the inputs
1

You could use try, and I'd rather see message than print.

> err_fun <- \(x) {
+   inputs <- try(x, silent=TRUE)
+   if (inherits(inputs, 'try-error')) {
+     stop("Check the inputs", call.=FALSE)
+   } else {
+     message("You can continue with the script")
+   }
+ }
> err_fun(a + b)
You can continue with the script
> err_fun(e + d)
Error: Check the inputs

Not the answer you're looking for? Browse other questions tagged or ask your own question.