The Art of R Programming

(WallPaper) #1

possible—and sometimes desirable from the point of view of the encapsu-
lation goal of object-oriented programming—to define a function within a
function; we are simply creating an object, which we can do anywhere.
Here, we haveh()being local tof(), just liked. In such a situation, it
makes sense for scope to be hierarchical. Thus, R is set up so thatd, which
is local tof(), is in turn global toh(). The same is true fory, as arguments
are considered locals in R.
Similarly, the hierarchical nature of scope implies that sincewis global
tof(), it is global toh()as well. Indeed, we do usewwithinh().
In terms of environments then,h()’s environment consists of whatever
objects are defined at the timeh()comes into existence; that is, at the time
that this assignment is executed:


h <- function() {
return(d*(w+y))
}


(Iff()is called multiple times,h()will come into existence multiple times,
going out of existence each timef()returns.)
What, then, will be inh()’s environment? Well, at the timeh()is created,
there are the objectsdandycreated withinf(),plusf()’s environment (w).
In other words, if one function is defined within another, then that inner
function’s environment consists of the environment of the outer one, plus
whatever locals have been created so far within the outer one. With multiple
nesting of functions, you have a nested sequence of larger and larger envi-
ronments, with the “root” consisting of the top-level objects.
Let’s try out the code:



f(2)
[1] 112



What happened? The callf(2)resulted in setting the local variabledto

8, followed by the callh(). The latter evaluatedd(w+y)—that is, (^8) (12+2)—
giving us 112.
Note carefully the role ofw. The R interpreter found that there was no
local variable of that name, so it ascended to the next higher level—in this
case, the top level—where it found a variablewwith value 12.
Keep in mind thath()is local tof()and invisible at the top level.



h
Error: object 'h' not found
It’s possible (though not desirable) to deliberately allow name conflicts
in this hierarchy. In our example, for instance, we could have a local vari-
abledwithinh(), conflicting with the one inf(). In such a situation, the
innermost environment is used first. In this case, a reference todwithinh()
would refer toh()’sd, notf()’s.
R Programming Structures 153


Free download pdf