Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Post History
Unlike some other languages, all scoping in R is dynamic. When R evaluates an expression like print(b), it looks up the function print in the current "environment", and later will look up the v...
Answer
#1: Initial revision
Unlike some other languages, all scoping in R is dynamic. When R evaluates an expression like `print(b)`, it looks up the function `print` in the current "environment", and later will look up the variable `b` in the same environment. ## Environments Environments are R objects that have two parts: a collection of named variables, and a parent environment. So if I want to evaluate `print(b)` in the environment `e`, R will try looking up `print` among the named variables in `e`. If that fails, it will try again in the parent of `e`, and so on, all the way back to the end of the chain, which is always a special environment called the "empty environment", with no variables and no parent. You can see the names of variables in `e` using `ls(e)`, and see the parent environment using `parent.env(e)`. ## Functions Functions in R are also R objects. They have three parts: a header, a body, and an environment. Normally the environment that is attached is the environment where the `function (...) ...` definition was evaluated, though it is possible to change it. It is called the "function environment". When you call a function, a new environment called the "evaluation environment" is created. It is populated with variables corresponding to the arguments in the header, and its parent is set to the function environment. So in the example ``` r f <- function() { b <- 2 print(a) print(b) } environment(f) f() ``` the function object `f` will be created in your workspace ("the global environment"), and will also have the global environment set as its environment. You can see this by running ``` r environment(f) #> <environment: R_GlobalEnv> ``` When you call `f` by running `f()`, a new evaluation environment will be created. Initially it won't hold any variables, because `f` has no arguments. Its parent will be the global environment (or whatever `environment(f)` happens to be at that point, if you changed it). As you evaluate the expressions during the call `f()`, the first line `b <- 2` will create a new variable in the evaluation environment. In the second line R will try to look up `print` there, but won't find it, so it will try `environment(f)`, but probably won't find it there either, and will go to its parent next, and so on. So that's why `g()` produced an error. The chain of environments from the evaluation environment of `g()` doesn't include the evaluation environment of `f()`, so it never sees the variable `b`. ## The Global Environment As I already mentioned, your workspace is called the global environment. You can access it as an environment object using ``` r globalenv() #> <environment: R_GlobalEnv> ``` It also has the name `.GlobalEnv`, so that's another way to get it: ``` r .GlobalEnv #> <environment: R_GlobalEnv> ``` So what is its parent? You can find out using the `parent.env()` function: ``` r g <- globalenv() parent.env(g) #> <environment: package:stats> #> attr(,"name") #> [1] "package:stats" #> attr(,"path") #> [1] "/Library/Frameworks/R.framework/Versions/4.3-x86_64/Resources/library/stats" ``` <sup>Created on 2023-10-01 with [reprex v2.0.2](https://reprex.tidyverse.org)</sup> This is the environment holding the objects exported from the second entry in my search list, the `stats` package: ``` r search() #> [1] ".GlobalEnv" "package:stats" "package:graphics" #> [4] "package:grDevices" "package:utils" "package:datasets" #> [7] "package:methods" "Autoloads" "tools:callr" #> [10] "package:base" ``` <sup>Created on 2023-10-01 with [reprex v2.0.2](https://reprex.tidyverse.org)</sup> Its parent will be the exports from the next item in the search list, etc., all the way back to the `base` package whose parent is the empty environment. So when you're looking up a function like `print` in the middle of a function call, R will look through the whole chain of environments until it finds it. Since `print` is actually defined in the `base` package, that's the one you'll get --- unless you've defined your own `print` function in your workspace, or some package in the search list has done that. I don't recommend that: `print` is used a lot, and you'll end up in a mess if you define it to something that doesn't print things! ## Functions in Functions Since functions in R are objects, they can be defined in other functions. For example, ``` r outer <- function() { a <- 1 inner <- function() { b <- 2 print(a) print(b) } inner() } outer() #> [1] 1 #> [1] 2 ``` <sup>Created on 2023-10-01 with [reprex v2.0.2](https://reprex.tidyverse.org)</sup> In this example, `inner` was created during the evaluation of `outer`, so `environment(inner)` will be the evaluation environment of that call. When it is evaluated and is looking for `a`, it won't find it locally, but will find it in the parent. ## That's not all... I've skipped over some important details: 1. Functions defined in packages. In general, the same scheme is used, but when a function is created in a package, it doesn't have its environment set to `globalenv()`, it gets an environment specific to the package. 2. Environments in tidyverse functions that use "tidy evaluation". Again, the same general scheme is used, but some tricks are used to set up special environments where arguments are evaluated.