0

Suppose I have a script Foo.r which looks like this.

source('Bar.r')
print("Hello World")

Now suppose further that in Bar.r, I want to return immediately if some condition is true, instead of executing the rest of the script.

if (DO_NOT_RUN_BAR) return; // What should return here be replaced with?
// Remainder of work in bar

In particular, if DO_NOT_RUN_BAR is set, I want Bar.r to return and Foo.r to continue execution, printing Hello World.

I realize that one way to do this is to invert the if statement in Bar.t and wrap the entire script inside an if statement that checks for the logical negation of DO_NOT_RUN_BAR, but I still want to know whether I can replace the return statement in the code above to skip execution of the rest of Bar.r when it is sourced.

merlin2011
  • 71,677
  • 44
  • 195
  • 329

3 Answers3

1

By defintion , source parse a file until the end of the file. So, I would split bar file in 2 parts :

source("bar1.R")
if (DO_RUN_BAR2) source("bar2.R")
print("Hello World")

This is safer than managing global variables with dangerous side effect.

agstudy
  • 119,832
  • 17
  • 199
  • 261
  • What I'm trying to achieve is that if multiple files source `bar`, `bar` will only get run once. This approach solves that problem but adds the overhead of having additional files for every file that is sourced. – merlin2011 Oct 30 '13 at 21:20
  • @merlin2011 I don't get your point here. But maybe [this](http://stackoverflow.com/questions/6456501/how-to-include-source-r-script-in-other-scripts) can help you... – agstudy Oct 30 '13 at 21:26
1

In Bar.r you can do

if (DO_NOT_RUN_BAR) stop();

Then in Foo.r you call it like this

try(source("./bar.r"), silent=T)
ndr
  • 1,427
  • 10
  • 11
0

Create your script with a multi-line expression with {...} enclosing it, and use stop in the middle:

{ print("test")
  print("test")
  print("test"); stop()
  print("test")
  print("test")
  print("test") }
#[1] "test"
#[1] "test"
#[1] "test"
#Error: 
IRTFM
  • 258,963
  • 21
  • 364
  • 487