I am a beginner in R. I want to be able to interrupt the currently running script if a condition is true. The closest thing I have found is the ps_kill function, which crashes Rstudio.
df <- data.frame(one = c(1,2,NA,4,NA), two = c(NA,NA,8,NA,10))
if (sum(is.na(df)) > 3)
{
ps_kill(p = ps_handle())
}
Is there a function I could use to replace ps_kill, to interrupt the script without crashing Rstudio ?
The stop function will throw an error and effectively terminate your script if you run it with Rscript or source. But keep in mind that this will terminate with an error. For instance:
# A function that will throw an error and quit
test <- function() {
print("This is printed")
stop()
print("this is not printed")
}
test()
Note that you can recover from an error throwing code by wrapping it in a try call:
# This will not throw an error and will not print the second sentence
try(test(), silent = TRUE)
Another solution if you really want to close R and not just finish your script, is to use the function q. This is not recoverable (it closes the R session).
I hope this answer your question!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With