Ussu20
Ussu20

Reputation: 199

tryCatch in R Programming

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.

Upvotes: 0

Views: 3203

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389215

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

Upvotes: 1

Limey
Limey

Reputation: 12586

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.

Upvotes: 3

Related Questions