Environments created by inheritance in this manner are generally
referred to by their memory locations. Here is what happened after adding
aprintstatement tof()(usingedit(), not shown here) and then running
the code:
>f
function(y) {
d<-8
h <- function() {
return(d*(w+y))
}
print(environment(h))
return(h())
}
> f(2)
<environment: 0x875753c>
[1] 112
Compare all this to the situation in which the functions are not nested:
>f
function(y) {
d<-8
return(h())
}
>h
function() {
return(d*(w+y))
}
The result is as follows:
> f(5)
Error in h() : object 'd' not found
This does not work, asdis no longer in the environment ofh(), because
h()is defined at the top level. Thus, an error is generated.
Worse, if by happenstance there had been some unrelated variabledin
the top-level environment, we would not get an error message but instead
would have incorrect results.
You might wonder why R didn’t complain about the lack ofyin the
alternate definition ofh()in the preceding example. As mentioned earlier,
R doesn’t evaluate a variable until it needs it under a policy called lazy evalu-
ation. In this case, R had already encountered an error withdand thus never
got to the point where it would try to evaluatey.
154 Chapter 7