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

后端 未结 5 1858
闹比i
闹比i 2020-12-08 22:24

Is there a way to source() a script in R such that it is attached as a parent to the global environment (.GlobalEnv)?

Curr

5条回答
  •  渐次进展
    2020-12-08 22:52

    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.

提交回复
热议问题