Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing default environment for assignment of new variables

Tags:

r

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?

like image 514
user697473 Avatar asked May 25 '12 18:05

user697473


3 Answers

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.

like image 67
joran Avatar answered Sep 19 '22 16:09

joran


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.

like image 25
Greg Snow Avatar answered Sep 19 '22 16:09

Greg Snow


Instead changing the environment, an easy way to do this is to save all variables in a list.

e <- list()
e$tmp <- 2
like image 21
xm1 Avatar answered Sep 18 '22 16:09

xm1