[R] on lexical scoping....

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Tue Apr 4 16:18:21 CEST 2023


On 04/04/2023 9:56 a.m., akshay kulkarni wrote:
> Dear Members,
>                               I have the following code typed at the console prompt:
> 
> y   <-   x*10
> 
> X has not been defined and the above code throws an object not found error. That is, the global environment does not contain x. Why doesn't it look further in the environment stack, like that of packages? There are thousands of packages that contain the variable named  x. Of course, that happens if the above code is in a function (or does it?).
> 
> What concept of R is at work in this dichotomy?
> 

First, some background:

Packages are associated with multiple environments.  There is the 
internal one that the package sees, and the external one that contains 
just the exports.

These are sometimes called the "package" environment and the "namespace" 
environment, but I don't think those names are used consistently. 
(There's another one containing the imports, but for these purposes, 
it's indistinguishable from the internal one.)

When a package is loaded by loadNamespace("pkg"), nothing happens in the 
global environment:  no new variables are visible.

When it is attached by library("pkg"), a lot more happens.  First, it is 
loaded as above, then the search list is modified.  The global 
environment is entry 1 in the search list; it stays there, but its 
"parent" is set to a copy of the external environment from the new 
package, and the parent of that environment is set to the previous 
parent, the second entry in the search list.

Okay, so now you search for "x" in the global environment, and it's not 
there.  It then goes to the other entries in the search list, which are 
typically external environments from various packages.  None of those 
packages export "x", so it is not found.

It doesn't matter if those packages use "x" without exporting it, 
because R won't look at internal environments in this kind of search.

And it doesn't matter what happens in other packages that are not on the 
search list (i.e. not "attached" because you never called library() or 
require() on them), because they just aren't in the chain of 
environments where R looks.

Duncan Murdoch



More information about the R-help mailing list