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

后端 未结 5 1852
闹比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:51

    From the source documentation, the local 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 to local, then attach 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 to local in source:

    tmp <- attach(what=NULL)
    source('test.R', local=tmp)
    

    or as a single line:

    source('test.R', local=attach(NULL))
    

提交回复
热议问题