Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop executing code in R

Tags:

r

I use data checks in my code, for example the following one:

if (...)
stop(paste('Warning: Weights do not sum up to 1')

The problem is that if the condition is true and the warning appears in the console, the code does not stop running. If hidden in a long code, one needs to scroll up always in the console output to see if a warning appeared.

Is there a way to tell R to interupt ALL code when the stop warning appears and the condition is true? Something like BREAK ?

I do not represent a reproducible example here because my code is quite long.

EDIT:

Here is a mini example:

When I execute

a=1+2

if (a==3)
  stop('a equals 3')


b=4

1+1

I would like to stop after printing

> a=1+2
> 
> if (a==3)
+   stop('a equals 3')
Error: a equals 3

but R executes everything, also the last part:

> a=1+2
> 
> if (a==3)
+   stop('a equals 3')
Error: a equals 3
>        
>        
> b=4
> 
> 1+1
[1] 2
like image 309
fuji2015 Avatar asked Mar 14 '23 08:03

fuji2015


1 Answers

According to stop, it only stops evaluation of the current expression. While I agree with Roland's comment to encapsulate your code into meaningful pieces via functions, a quick hack would be to wrap all your current code in curly braces. That will make it appear to the R parser as a single expression.

R> # without curly braces
R> x <- 1
R> y <- 2
R> if (x < y)
+   stop("x < y")
Error: x < y
R> print("hello")
[1] "hello"
R>
R> # with curly braces
R> {
+   x <- 1
+   y <- 2
+   if (x < y)
+     stop("x < y")
+   print("hello")
+ }
Error: x < y
like image 185
Joshua Ulrich Avatar answered Mar 16 '23 21:03

Joshua Ulrich