Is there any way to change the set the working environment or workspace in R to a defined environment? I'd like to call the variables in an environment without constantly referring to the environment. I understand that the attach function can be used to access the variable in this manner, but any variables created don't get placed back in the attached environment. The goal is to have all the functions take place in the other environment.
For example:
original.env <- .GlobalEnv
other.env <- new.env()
other.env$A <- 12; other.env$B <- 1.5
set.env(other.env)
C <- A + B
set.env(original.env)
other.env$C
[1] 13.5
It's the step with set.env
which I can't figure out if it exists, or there's some other trick to doing this.
The goal of this approach is to allow the same code to be used on different data sets with identical structures in several non-nested environments without constantly calling other environments with the Environment$
prefix, which gets really verbose in many cases.
If the results can also be assigned back to the set environment (as in the global environment, everything has an implicit .GlobalEnv$
in front of any variable) it would make it way easier to access and return multiple values from inside of a function.
Any help is appreciated. Thanks.
You are looking for eval
/ evalq
From help("evalq")
Evaluate an R expression in a specified environment.
Specifically, evalq
noting
The evalq form is equivalent to eval(quote(expr), ...). eval evaluates its first argument in the current scope before passing it to the evaluator: evalq avoids this.
# Therefore you want something like this
evalq(C <- A + B, envir = other.env)
If you want to wrap more than one expression use {}
eg
evalq({C <-A + B
d <- 5
}, envir = other.env)
How about using with
?
original.env <- .GlobalEnv
other.env <- new.env()
other.env$A <- 12; other.env$B <- 1.5
with(other.env, { C <- A + B ; FOO <- 'bar' })
other.env$C
[1] 13.5
other.env$FOO
[1] "bar"
来源:https://stackoverflow.com/questions/32063700/changing-the-functional-global-environment-in-r