[R] Understanding R's "Environment" concept

Duncan Murdoch murdoch.duncan at gmail.com
Tue Jul 19 13:15:40 CEST 2011


On 11-07-18 2:16 PM, Nipesh Bajaj wrote:
> Hi all, I am trying to understand the R's "environment" concept
> however the underlying help files look quite technical to me. Can
> experts here provide me some more intuitive ideas behind this concept
> like, why it is there, what exactly it is doing in R's architecture
> etc.?
>
> I mainly need some non-technical intuitive explanation.
>

There are three characteristics that describe environments:

1.  They are a collection of named objects.  Much of the time when you 
ask for something by name, you're looking in an "environment" to find it.

2.  They have a child-parent relationship to another environment.  Some 
of the time, when you look up a name and it is not found, it goes to the 
parent to look.  (And then the grandparent .... )  This means most of 
the time when you specify a name, R just looks in one environment and 
its ancestors to find the object.

3.  They don't get copied when you make an assignment.  So you can say
env <- globalenv(), and your env is another name for the global 
environment, which is where most user objects are created.  Saying

env$z <- 3

will create a new variable named z in the global environment.  This 
differs from most other R objects, where assignment makes an independent 
copy.

And one thing that says how they are used:

1.  Things like functions need to look up names all the time.  Those 
things generally have an associated environment which is where they'll 
look.  (Functions are a little complicated in that they get a new one 
every time you call them, but they also have an associated environment 
which is the parent of the new one.)

Duncan Murdoch



More information about the R-help mailing list