ABSTRACT

In chapter 7 you will learn about environments, the data structure that powers scoping. This chapter dives deep into environments, describing their structure in depth, and using them to improve your understanding of the four scoping rules described in the “Lexical scoping” section of the functions chapter. Understanding environments is not necessary for day-to-day use of R. But they are important to understand because they power many important R features like lexical scoping, namespaces, and R6 classes, and interact with evaluation to give you powerful tools for making domain specific languages, like dplyr and ggplot2.

“Environment basics” introduces you to the basic properties of an environment and shows you how to create your own. “Recursing over environments” provides a function template for computing with environments, illustrating the idea with a useful function. “Special environments” describes environments used for special purposes: for packages, within functions, for namespaces, and for function execution. “Call stacks” explains the last important environment: the caller environment. This requires you to learn about the call stack, that describes how a function was called. You’ll have seen the call stack if you’ve ever called traceback() to aid debugging. “As data structures” briefly discusses three places where environments are useful data structures for solving other problems.