Using `source()` while executing a local job

I am trying to execute as local job the following file, let's call it main.R:

# This is main.R
x <- 1

The main point here is that I am sourcing another file (secondary.R) which relies on the existence of x like this:

# This is secondary.R
y <- x + 1

It seems like R Studio executes secondary.R in a new environment, as it seems to have no knowledge of x and the local job fails with this message:

Error in eval(ei, envir) : object 'x' not found
Calls: sourceWithProgress ... eval -> eval -> source -> withVisible -> eval -> eval
Execution halted

I have 2 questions at this point:

  1. Is that a correct representation?

  2. If yes, why is that the case and how to avoid this behavior?


Hi @valeri. I cannot repeat the problem but you may try to force the source file to evaluate in the environment that source was called. Hope it can help.

x <- 1
source("secondary.R", local = TRUE)

Works - thanks a lot!

This is a known issue. See here for more info:

Thanks @jonathan - does this mean that it is expected that this behaviour will change in the future?

We'll change it in the future (as noted in the bug and here it's really too surprising to leave as a default). The current behavior exists in order to make it easy to capture all of the objects created by a script, and there are other ways to do that.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.