Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stop execution script within condition

Tags:

r

break

I have the following code in the script test.R:

if (x==2){
  stop("the script ends")
}

Now I source this script

source(test.R)
t <- 2

I would like the code to stop if x==2 and does not go further. However, it continues and assigns t <- 2. I can use the function warnings(options) but I want to avoid this option and implement a condition within the if. Any suggestion?

like image 982
richpiana Avatar asked Dec 04 '25 18:12

richpiana


1 Answers

The code you list should work as expected.

As an example, I made two scripts, test.R and test2.R:

1. File test.R:

if (identical(x, 2)) {
  stop("the script ends")
}

(Note: I'm using identical(x, 2) as the safer way to check whether x equals 2, but x == 2 would work the same in this example.)

2. File test2.R:

x <- 1
source("test.R")
t <- 1
print("This should be printed.")

x <- 2
source("test.R")
t <- 2
print("This should not be printed!")

Now I run test2.R from the console:

> t <- 5
> source('test2.R')
[1] "This should be printed."
 Error in eval(ei, envir) : the script ends 
> t
[1] 1

We see that the check passed the first time, when x == 1, and it failed the second time, when x == 2. Therefore, the value of t at the end is 1, because the first assignment was run and the second was not.

like image 186
Claus Wilke Avatar answered Dec 07 '25 09:12

Claus Wilke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!