1

I need to run two R scripts in sequence. I am not asking about running scripts in parallel.

Each script has a stop-if-error logic inside. So if I run either of them separately, the execution will halt when an error occurs. The problem is, when I put them in a wrapper code like this:

source('script1.r', echo=T)
source('script2.r', echo=T)

and when an error occurs in script1.r, R will move on to execute script2.r.

How do I tell R to stop completely and not to move on in such a scenario?

2 Answers 2

1

I would wrap the code in the two scripts in functions, source the scripts and then call the functions in the main file. If one function fails the script should stop.

(This may depend on how you execute the script, for example if you select code in Rstudio and run by CMD+Enter it will continue after errors.)

Sign up to request clarification or add additional context in comments.

1 Comment

The problem was with RStudio. If I run it from command line, it will stop when the error in script1 occurs.
0

You could do something with try(). I put the following in script1.R:

stop("Stop")

In script2.R I have

print("A")

Then from a "master script", I call

x <- try(source("script1.R", echo = TRUE))
#> 
#> > stop("Stop")
if ( !inherits(x, "try-error") ) {
    source("script2.R", echo = TRUE)
}

Created on 2019-01-31 by the reprex package (v0.2.1)

If the stop() portion is called (or any error occurs), x will be of class try-error, and the second source() call will not be executed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.