The Art of R Programming

(WallPaper) #1
the same function but with a restrictedxrange. But suppose you wish to dis-
play the original plot and the close-up one in the same picture. Here, we will
develop a function, which we’ll nameinset(), to do this.
In order to avoid redoing the work thatcurve()did in plotting the orig-
inal graph, we will modify its code slightly to save that work, via a return
value. We can do this by taking advantage of the fact that you can easily
inspect the code of R functions written in R (as opposed to the fundamen-
tal R functions written in C), as follows:

1 > curve
2 function (expr, from = NULL, to = NULL, n = 101, add = FALSE,
3 type = "l", ylab = NULL, log = NULL, xlim = NULL, ...)
4 {
5 sexpr <- substitute(expr)
6 if (is.name(sexpr)) {
7 # ...lots of lines omitted here...
8 x <- if (lg != "" && "x" %in% strsplit(lg, NULL)[[1]]) {
9 if (any(c(from, to) <= 0))
10 stop("'from' and 'to' must be > 0 with log=\"x\"")
11 exp(seq.int(log(from), log(to), length.out = n))
12 }
13 else seq.int(from, to, length.out = n)
14 y <- eval(expr, envir = list(x = x), enclos = parent.frame())
15 if (add)
16 lines(x, y, type = type, ...)
17 else plot(x, y, type = type, ylab = ylab, xlim = xlim, log = lg, ...)
18 }

The code forms vectorsxandy, consisting of thex- andy-coordinates
of the curve to be plotted, atnequally spaced points in the range ofx. Since
we’ll make use of those ininset(), let’s modify this code to returnxandy.
Here’s the modified version, which we’ve namedcrv():

1 > crv
2 function (expr, from = NULL, to = NULL, n = 101, add = FALSE,
3 type = "l", ylab = NULL, log = NULL, xlim = NULL, ...)
4 {
5 sexpr <- substitute(expr)
6 if (is.name(sexpr)) {
7 # ...lots of lines omitted here...
8 x <- if (lg != "" && "x" %in% strsplit(lg, NULL)[[1]]) {
9 if (any(c(from, to) <= 0))
10 stop("'from' and 'to' must be > 0 with log=\"x\"")
11 exp(seq.int(log(from), log(to), length.out = n))
12 }
13 else seq.int(from, to, length.out = n)
14 y <- eval(expr, envir = list(x = x), enclos = parent.frame())
15 if (add)

278 Chapter 12

Free download pdf