This section will talk about how we use environments and it's utility
functions including environment()
, assign()
,
eval()
, get()
,
etc.
Basically, your current working environment is in .GlobalEnv
,
and each function has it's own environment.
.GlobalEnv
.
Note that the parent of "a.new.env" is "<environment: base>" rather than
"a.base"!!
The following example fixes this.
- assign(), eval(), and get()
```
rm(list = ls())
.GlobalEnv
parent.env(a.parent.env <- new.env())
### Two of the followings are the same.
assign("a.children.env", new.env(), envir = a.parent.env)
eval(parse(text = "a.children.env <- new.env()"), envir = a.parent.env)
### Two of the followings are the same.
ls()
eval(ls(), envir = a.parent.env)
### There is a object inside "a.parent.env".
ls(envir = a.parent.env)
assign("a.value", 10, envir = a.parent.env)
eval(parse(text = "a.value <- a.value + 1"), envir = a.parent.env)
### There are two objects now.
ls(envir = a.parent.env)
### This should return 11.
get("a.value", envir = a.parent.env)
```
There is a parent environment attached in .GlobalEnv
,
and a childrend
environment attached inside the parent environment.
In different environment,
the assign()
and eval()
can alter the objects, and
get()
can access the object values.
- Function is a TEMPORARY environment
```
rm(list = ls())
parent.env(.GlobalEnv) ### This is an interesting result.
a.function <- function(){
a <- 1
print(environment()) ### print current environment
environment()
}
an.env <- a.function() ### This is an interesting environment.
an.env ### This should be the same as the above.
ls(envir = an.env)
get("a", envir = an.env)
```
I create an environment where is created by a.function()
and executing itself,
then I store the environment in .GlobalEnv.
---