0

In R, I want to create a function that return Flag=0 if it encounters any error:

Error<-function(x){
       tryCatch(x,
       error=function(e{
       Flag=0
         }
      )
}

When I enter: Error(5+b). It does not reflect Flag=0.

Ussu20
  • 129
  • 1
  • 12
  • What do you mean, *"return Flag=0"* ... do you mean that it returns a named vector or list, as in `list(Flag=0)`, or are you trying to assign the value `0` to an object named `Flag` in the calling environment? Or do you just want it to return `0`? – r2evans Mar 03 '21 at 13:30
  • Assign value of 0 – Ussu20 Mar 03 '21 at 13:45
  • 1
    Okay, you'll need to break scope and go against functional programming to do that. While I think it's bad practice to assign a new variable into the calling (or global) environment, you can do that with `assign`. The use of `<<-` (as in the answer) somewhat works, but does not allow you to control in which environment the variable is placed. For instance, if this is called from another function, then (1) if that function has a `Flag` object in its environment, then that object is assigned `0`, otherwise (2) `Flag` is created/overridden in the global environment. – r2evans Mar 03 '21 at 14:27

2 Answers2

2
Flag <- 1

tryCatch(
  5+b,
  error=function(e) { Flag <<- 0}
)

Flag
[1] 0

In your code, the scope of Flag is local to the error handler. Using <<- makes the assignment in the global environment.

Limey
  • 10,234
  • 2
  • 12
  • 32
  • Instead if I use tryCatch(x,..) and outside the function, I define few expressions as: y<-20, a<-5 and x<- sqrt(y)+ a+"b". error(x) does not return Flag=0 – Ussu20 Mar 03 '21 at 13:48
  • @r2evan's comments above are worth noting. I accept my answer here is a simplistic approach that does not cater for every situation. – Limey Mar 03 '21 at 14:59
1

You can return a string ('error') here if error occurs and check it's value to return 1/0.

Error<-function(x){
  y <- tryCatch(x,error=function(e) return('error'))
  as.integer(y != 'error')
}

Error(sqrt('a'))
#[1] 0
Error(sqrt(64))
#[1] 1
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • I don't want tryCatch to evaluate and return output, I have a function that throws error. I just want it to assign a value of 0 if there is an error and a value of 1 if no error. can you please help with this? – Ussu20 Mar 03 '21 at 14:29