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?
Perhaps someone can improve on this, removing the need to quote the variable name:
e <- new.env()
`%=%` <- function(x,y) {assign(x,y,envir = e)}
"d" %=% 5
e$d
[1] 5
But this feels kind of silly to me. Maybe just use assign
directly? More typing, maybe, but it does what you want with less danger.
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
.
Instead changing the environment, an easy way to do this is to save all variables in a list.
e <- list()
e$tmp <- 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With