Search code examples
rr-environment

Source script to separate environment in R, not the global environment


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)

enter image description here


Solution

  • The following environment insertion appears to achieve the desired functionality:

    Check the current search path:

    search()
    # [1] ".GlobalEnv"        "package:stats"     "package:graphics"
    # [4] "package:grDevices" "package:utils"     "package:datasets"
    # [7] "package:methods"   "Autoloads"         "package:base"
    

    Add new environment for sourced packages and use local parameter when source()ing:

    myEnv <- new.env()    
    source("some_other_script.R", local=myEnv)
    attach(myEnv, name="sourced_scripts")
    

    Check the search path:

    search()
    #  [1] ".GlobalEnv"        "sourced_scripts"   "package:dplyr"
    #  [4] "package:stats"     "package:graphics"  "package:grDevices"
    #  [7] "package:utils"     "package:datasets"  "package:methods"
    # [10] "Autoloads"         "package:base"
    

    Note that we attach() the new environment after sourcing, so that dplyr is attached after our script environment in the search path.