Friday, February 27, 2015

Environments in R

An environment is a special term in R, but its concept is used in many interpreters of programming languages. The term of variable scope is directly related with environments. An environment in R encapsulates a couple of variables or objects which itself is encapsulated by a special environment called global environment.

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


Value of t is still 12 because we create an other t variable which is encapsulated by the environment my.env.


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



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