--Hi,
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
Have you looked at stopifnot?
yes, it changes nothing, the program continu to read to the end of code.
How are you running your code? Sourcing an entire file? Line-by-line with ctrl+Enter? Called as a script from command line? Something else?
What happens if you run this:
if(TRUE){
message("first")
} else{
message("second")
}
What happens if you run that:
if(TRUE){
stop("first")
} else{
message("second")
}
i select entire code in R-studio and then i run the code.
So what happens if you run my above lines with this method?
> if(TRUE){
+ message("first")
+ } else{
+ message("second")
+ }
first
> if(TRUE){
+ stop("first")
+ } else{
+ message("second")
+ }
Error : first
Then you can just use stop()
instead of your previous exit()
, I believe it does what you want?
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.
ok, thank you;
i'm going to try your method.