Search code examples
rrstudiodata-analysis

Halt R script (run interactively) if a condition is not met


Use case: I do interactive data analysis in RStudio, i.e. I highlight a bunch of code and hit run. Sometimes there are conditions that would statistically invalidate my analysis even though my code would still run fine. I want to stop the code or throw some very wild error in these cases.

Minimal working example:

stopifnot(TRUE, FALSE)
x <- 42

If I highlight the two lines and run, 42 is still assigned to x. That is bad -- I don't want any line after stopifnot(TRUE, FALSE) to run (since they are statistically invalid, while programmatically fine). Is there a way to stop the code totally if the condition is not met?


Solution

  • My solution is to wrap the code in brackets:

    {
      stopifnot(TRUE, FALSE)
      x <- 42
    }