The Art of R Programming

(WallPaper) #1

7.8.2 Writing to Nonlocals with assign()................................


You can also use theassign()function to write to upper-level variables. Here’s
an altered version of the previous example:



two
function(u) {
assign("u",2u,pos=.GlobalEnv)
z<-2
z
}
two(x)
x
[1] 1
u
[1] 2



Here, we replaced the superassignment operator with a call toassign().

That call instructs R to assign the value (^2) u(this is the localu) to a variable
ufurther up the call stack, specifically in the top-level environment. In this
case, that environment is only one call level higher, but if we had a chain of
calls, it could be much further up.
The fact that you reference variables using character strings inassign()
can come in handy. Recall the example in Chapter 5 concerning analysis of
hiring patterns of various large corporations. We wanted to form a subdata
frame for each firm, extracted from the overall data frame,all2006. For in-
stance, consider this call:
makecorpdfs(c("MICROSOFT CORPORATION","ms","INTEL CORPORATION","intel","
SUN MICROSYSTEMS, INC.","sun","GOOGLE INC.","google")
This would first extract all Microsoft records from the overall data frame,
naming the resulting subdata framems2006. It would then createintel2006for
Intel, and so on. Here is the code (changed to function form, for clarity):
makecorpdfs <- function(corplist) {
for (i in 1:(length(corplist)/2)) {
corp <- corplist[2
i-1]
newdtf <- paste(corplist[2*i],"2006",sep="")
assign(newdtf,makecorp(corp),pos=.GlobalEnv)
}
}
In the iterationi=1, the code usespaste()to splice together the strings
"ms"and"2006", resulting in"ms2006", the desired name.
R Programming Structures 163

Free download pdf