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.
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.
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
list(Flag=0), or are you trying to assign the value0to an object namedFlagin the calling environment? Or do you just want it to return0?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 aFlagobject in its environment, then that object is assigned0, otherwise (2)Flagis created/overridden in the global environment.