1. Environments
Let's take a break from thinking about functions to discuss environments. You'll need to understand how this variable type works before we discuss variable scope in the next lesson.
2. Environments are like lists
Environments are a type of variable that is used to store other variables. Most of the time, you can think of environments as special lists. Let's see an example, using some facts about DataCamp.
Here are its contents. I've used ls-dot-str to list the elements. It's a hybrid of the ls and str functions, that can give a compact summary of multiple variables at once.
Let's convert the list to an environment using list2env. Calling ls-dot-str shows exactly the same output, since the contents are the same. So far, so unremarkable.
3. Environments have parents
From the point of view of writing functions, the most important difference between environments and lists is that environments have a parent. You can think of the environments as being inside their parents.
The parent of the environment also has a parent, and so they form a sequence, just like these matryoshka dolls.
4. Getting the parent environment
To find the parent of an environment, you call parent-dot-env.
The print method for environments is a bit rubbish, so to display them, I prefer to call environmentName.
The parent of datacamp_env is the global environment. This is used to store any variables that you define at R's command prompt.
This environment also has a parent. Calling parent-dot-env again, you can see that it's the stats package. When an R package is loaded, it gets an environment to store all its functions and other variables.
If we kept calling parent-dot-env where would we end up?
The search function shows all the parent environments from the global environment onwards.
At the end, the base environment has a special environment called the empty environment, which is equivalent to the biggest doll in the set.
5. Does a variable exist?
Let's take founding_year out of datacamp_env and put it in the global environment.
You can test for the existence of a variable in an environment using exists. Do you think founding_year exists in datacamp_env?
It does! That might not be what you expected, since founding_year is actually in the global environment, not datacamp_env. If R cannot find a variable in an environment, it will look in the parent, then the grandparent, and so on until it finds it.
You can think of the exists function as a greedy child. If the environment doesn't have the variable it wants, it will ask the parent, and if the parent says "no", it will asked the grandparent, and keep going until it gets what it wants, or there are no ancestors left to ask.
You can force R to only look in the environment you asked for by setting inherits to FALSE.
6. Let's practice!
Time to explore some environments.