The Art of R Programming

(WallPaper) #1
The fix is to passdandyas arguments:


f
function(y) {
d<-8
return(h(d,y))
}
h
function(dee,yyy) {
return(dee*(w+yyy))
}
f(2)
[1] 88



Okay, let’s look at one last variation:


f
function(y,ftn) {
d<-8
print(environment(ftn))
return(ftn(d,y))
}
h
function(dee,yyy) {
return(dee*(w+yyy))
}




w<-12
f(3,h)



[1] 120

Whenf()executed, the formal argumentftnwas matched by the actual
argumenth. Since arguments are treated as locals, you might guess thatftn
could have a different environment than top level. But as discussed, a clo-
sure includes environment, and thusftnhash’s environment.
Note carefully that all the examples so far involving nonlocal variables
are for reads, not writes. The case of writes is crucial, and it will be covered
in Section 7.8.1.


7.6.3 More on ls()....................................................


Without arguments, a call tols()from within a function returns the names
of the current local variables (including arguments). With theenvirargu-
ment, it will print the names of the locals of any frame in the call chain.


R Programming Structures 155
Free download pdf