Reputation: 199
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
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
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