The Art of R Programming

(WallPaper) #1
[1] 1
b:
[1] 2
a:
[1] 1

To see how this works, we’ll first look at theget()function, one of the
most useful utilities in R. Its job is quite simple: Given the name of an object,
it fetches the object itself. Here’s an example:

> m <- rbind(1:3,20:22)
>m
[,1] [,2] [,3]
[1,]123
[2,] 20 21 22
> get("m")
[,1] [,2] [,3]
[1,]123
[2,] 20 21 22

This example withminvolves the current call frame, but in ourshowframe()
function, we deal with various levels in the environment hierarchy. So, we
need to specify the level via theenvirargument ofget():

vrg <- get(vr,envir=env)

The level itself is determined largely by callingparent.frame():

if (upn < 0) {
env <- .GlobalEnv
} else {
env <- parent.frame(n=upn+1)
}

Note thatls()can also be called in the context of a particular level, thus
enabling you to determine which variables exist at the level of interest and
then inspect them. Here’s an example:

vars <- ls(envir=env)
for (vr in vars) {

This code picks up the names of all the local variables in the given frame
and then loops through them, setting things up forget()to do its work.

7.7 No Pointers in R............................................................


R does not have variables corresponding topointersorreferenceslike those
of, say, the C language. This can make programming more difficult in some

R Programming Structures 159
Free download pdf