Is there a way to source()
a script in R such that it is attached as a parent to the global environment (.GlobalEnv
)?
Currently, when I source a script, all variables and functions of that script appear in my global (interactive) environment. I'd like to include these variables and functions in the search path, but not in .GlobalEnv
. That is, I'd like the sourced script to behave like an attached package, which gets attached between the global and base environments (see figure from Advanced R Environments)
The following environment insertion appears to achieve the desired functionality:
Check the current search path:
Add new environment for sourced packages and use
local
parameter whensource()
ing:Check the search path:
Note that we
attach()
the new environment after sourcing, so thatdplyr
is attached after our script environment in the search path.From the
source
documentation, thelocal
argument can be an environment which determines where the sourced expressions are evaluated.This suggests that you could create a new environment, run
source
passing this environment tolocal
, thenattach
the environment to the search path.Or you can use attach with
what=NULL
to create an empty environment, save the return value, and pass that tolocal
insource
:or as a single line:
I'm not sure if my answer is any different from the answers given above, but I use the following code:
I would also like to a solution using
sys.source
function. Usingenvir
andtoplevel.env
arguments allows for convenient (IMHO) bypassing of the global environment. As per the linked documentation:where
tst.R
contains:Results:
The simplest way to source a script as if it was a package (i.e. such that lexical scoping won't result in the use of variables defined in the global environment when calling functions defined in your R script) is to create an environment that that is whose parent is the
.BaseNamespaceEnv
, and then callsource()
using that environment.For example if you have a script like this:
Then evaluating the following at the console, won't generate an error, as it would if
my_fun
were defined within it's own package:However, if you create an environment whose
search()
path does not include the Global Environment (.GlobalEnv
) then you'll get a proper error when you call the function from your script: