user697473 user697473 - 4 months ago 50
R Question

changing default environment for assignment of new variables

I often want to create many variables in an environment under the global environment. This can be done easily with the

argument to
-- 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

Instead, I would like a command that lets me change the default environment for assignment of new variables. For example:

e <- new.env()
tmp <- 2
e$tmp # 2
.GlobalEnv$tmp # Error: object 'tmp' not found

isn't a real command.

Is there any safe way to do this sort of thing in R?


The evalq function will evaluate its first argument in a specified environment, so you could create your new environment, then wrap the assignments into evalq.