After setting a variable to a value out of any function and class, the default holder of this variable is the global environment.
Suppose we set t to 10 by
t <- 10
and this is the same as writing
assign(x="t", value=12, envir=.GlobalEnv)
and the value of t is now 12:
> t <- 10
> assign(x="t", value=12, envir=.GlobalEnv)
> t
[1] 12
Instead of using the global environment, we can create new environments and attach them to parent environments. Suppose we create a new environment as below:
> my.env <- new.env()
> assign(x="t", value="20", envir=my.env)
> t
[1] 12
Variables in environments are accessable using the assign and the get functions.
> get(x="t", envir=my.env)
[1] "20"
> get(x="t", envir=.GlobalEnv)
[1] 12
As we can see, values of the variables with same name are different, because they are encapsulated by separate environments.
exists() function returns TRUE if an object exists in an environment else returns FALSE. Examining existence of an object is crucial in some cases.
> exists(x="t", envir=.GlobalEnv)
[1] TRUE
> exists(x="t", envir=my.env)
[1] TRUE
> exists(x="a", envir=my.env)
[1] FALSE
is.environment() function returns TRUE if an object is an environment else returns FALSE.
> is.environment(.GlobalEnv)
[1] TRUE
> is.environment(my.env)
[1] TRUE
> is.environment(t)
[1] FALSE
Finally, environments are simply lists and a list can be converted to an environment easly.
> my.list <- list (a=3, b=7)
> my.env <- as.environment(my.list)
> get("a", envir=my.env)
[1] 3
> get("b", envir=my.env)
[1] 7
> my.env <- as.environment(my.list)
> get("a", envir=my.env)
[1] 3
> get("b", envir=my.env)
[1] 7
The inverse process is converting an environment to a list:
> as.list(.GlobalEnv)
$t
[1] 12
$my.env
$my.list
$my.list$a
[1] 3
$my.list$b
[1] 7
Happy R days :)
No comments:
Post a Comment
Thanks