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.

3
  • 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? Commented Mar 3, 2021 at 13:30
  • Assign value of 0 Commented Mar 3, 2021 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. Commented Mar 3, 2021 at 14:27

2 Answers 2

3
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.

Sign up to request clarification or add additional context in comments.

2 Comments

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
@r2evan's comments above are worth noting. I accept my answer here is a simplistic approach that does not cater for every situation.
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

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.