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 ?
CodePudding user response:
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!
CodePudding user response:
If you have long running code you can try the 'Stop' button right top side of your console panel in R studio.
As shown in this screenshot. https://prnt.sc/1txafh0
Hope this is what you're looking for!
CodePudding user response:
The stop()
function returns an error if called, so you can use this. The only trick is that if you're using it in interactive mode, you need to wrap all the code that you want to skip in a set of braces, e.g.
df <- data.frame(one = c(1,2,NA,4,NA), two = c(NA,NA,8,NA,10))
{
if(sum(is.na(df)) > 3) stop("More than three NAs")
print("don't run this")
}
# Error: More than three NAs
Note the braces include the print line, otherwise stop would just carry on running the code after the line that causes an error, e.g.
if(sum(is.na(df)) > 3) stop("More than three NAs")
# Error: More than three NAs
print("don't run this")
# [1] "don't run this"
CodePudding user response:
If you are running in interactive mode (like you said in your comment), stopApp should terminate the process without causing an error.