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 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"