Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

For many years as an R user, I didn’t care about environments. To run your statistics, you only very rarely need them. Until you come accross your first environmental concerns…

For me, that was in relation with reference classes and R6 objects. Suddenly, everybody was talking about env, and I didn’t have a clue.

So, here’s a primer. For a long discussion, it may be worth referring to the excelent chapter in Hadley Wickham’s book.

If you are coming from an OO background (such as Java, C#), it may even be the case that environments are less confusing to you than the rest in R. The reason is that R environments have reference semantics, which is very natural in Java and C#. For the others: What this means is that, for example, multiple names can point to he same memory location (aka object). This is not normally the case in R. In R, even a list behaves like an inmutable string in Java/C#:

> a <- list(v1=1, v2=2)
> b <- a
> identical(a, b)
[1] TRUE
> a$v1 <- 3 > identical(a, b) [1] FALSE In R, environments behave more like what we know from Java/C#: e1 <- new.env() e1$v1 <- 1
e1$v2 <- 2 as.list(e1)$v1
[1] 1

$v2 [1] 2 e2 <- e1 e1$v1 <- 3
e2\$v1
[1] 3

Also, environments are conceptually similar to namespaces. The main reason of existence of environments is that they organise how R finds objects by name. For example, two packages could have a function of the same name. So, if you load both packages, which one is called? In that specific case, it would be the package that was loaded last.

More precisely, environments are chained. Each environment (except the emptyenv()) has a parent. When accessing an object by name, then R starts in the globalenv(), and then follows along parents until it finds the name.

Here are a few common functions in relation to environments. But again: this is a rather advanced topics, so you can still do lots of things without grasping this.

# Show a list of the attached packages, and their order.
# As each package has its environment, this tells you the
# order with with R searches for varibalse
search()

#Returns the environment of a function:
environment(print)

#Checks wether an name exists in a specific environment
exists("cost", envir = e, inherits = FALSE)

The post What is an R environment? appeared first on ipub.