i'm looking a function to exit code if condition statement is statisfied, like that:
i've tried the code below but the program continu to read the else block.
exit <- function() {
.Internal(.invokeRestart(list(NULL, NULL), NULL))
}
assert=1
if(assert){
exit()
}else{
code to run
}
thx
The function stop("error message") is to stop with an error.
If you're running an entire script by hand and you don't want the code after if/else to be run if assert is FALSE, that would be the simplest way: you make an assertion assert, if it's wrong you consider that as an error and stop the script immediately, if assert is not wrong, you continue with no error.
The other common way to do that would be to have all that code inside a function, and have an early return() in the if code:
my_function(){
assert <- FALSE
if(assert){
return()
}
# code here, only run if assert == FALSE
result <- operation()
return(result)
}
my_function()
If you want to run the entire script by hand and not get any error message, you could put everything else in the else block:
assert <- FALSE
if(assert){
message("We do nothing here")
} else{
# code here
result <- operation()
}
# no code outside the `else`
that can be a lot of code in the else block.
It's not totally impossible to stop without error message, but it's stretching normal R usage. It's an indication that maybe you should be using a function.