'stop execution script within condition

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?



Solution 1:[1]

A while loop can create a condition that you can escape from as you are suggesting:

while (TRUE){
    if (x==2) {
        break
    }
}

This is assuming that your code is 'all the way to the left' when executing. Seeing a little more might help, or better understanding how x is being set or being used. Note that using something like while(TRUE) might not be best practice, and can lead to infinite execution if you do not exit properly.

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 boethius
Solution 2