Understanding lexical scoping in R Understanding lexical scoping in R r r

Understanding lexical scoping in R


Normally when discussed in the context of R lexical scoping means that free variables in a function (i.e. variables that are used in a function but not defined in the function) are looked up in the parent environment of the function, as opposed to the environment of the caller (also referred to as the parent frame) but there are no free variables in with.default so the example does not illustrate a violation of lexical scoping in that sense.

For example, this illustrates lexical scoping:

x <- 1f <- function() xg <- function() { x <- 0; f() }g() # 1

The answer is 1 because 1 is defined in the environment that f is defined in. Had R used dynamic scoping rather than lexical scoping the answer would have been 0 (using the environment of the caller). We can illlustrate how R can emulate dynamic scoping like this:

f <- function() eval.parent(quote(x))g() # 0

ADDED:

In a comment below @hadley suggested that the authors may have been referring to the fact that the second actual argument to with.default is not evaluated lexically and this interpretation seems likely. Instead of being evaluated relative to the surrounding lexical environment the second actual argument of with.default is read into the with.default function as an expression using substitute and then evaluated relative to the first argument using eval. There is some question of what the definition of lexical scoping ought to be as it is rarely defined even when extensively discussed but typical discussions in relation to R refer to it as the treatment of free variables. See for example Gentleman & Ihaka.