I often want to create many variables in an environment under the global environment. This can be done easily with the envir argument to sys.source — if all of the variables created by the file that one is sourcing are supposed to go into a single environment.
But I typically work with a file that creates sets of variables. One set should go into one environment, another set should go into another environment, and so on. I don’t want to split this file into multiple files and then make multiple calls to sys.source.
Instead, I would like a command that lets me change the default environment for assignment of new variables. For example:
e <- new.env()
setDefaultEnvironment(e)
tmp <- 2
e$tmp # 2
.GlobalEnv$tmp # Error: object 'tmp' not found
But setDefaultEnvironment isn’t a real command.
Is there any safe way to do this sort of thing in R?
The
evalqfunction will evaluate its first argument in a specified environment, so you could create your new environment, then wrap the assignments intoevalq.