What is an R environment?

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#:

In R, environments behave more like what we know from Java/C#:


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.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.