Flexible Handling of Arguments to Functions
Because of the lazy evaluation practised by R, it is very simple to deal with missing arguments in function calls, giving the user the opportunity to specify the absolute minimum number of arguments, but to override the default arguments if they want to. As a simple example, take a function plotx2 that we want to work when provided with either one or two arguments. In the one-argument case (only an integer x> 1 provided), we want it to plot z2 againstz for z = 1 to x in steps of 1. In the second case, when y is supplied, we want it to plot y against z for z = 1 to x.
plotx2 <- function (x, y=z^2) { z<-1:x plot(z,y,type="l") }
In many other languages, the first line would fail because z is not defined at this point. But R does not evaluate an expression until the body of the function actually calls for it to be evaluated (i.e. never, in the case where y is supplied as a second argument). Thus for the one-argument case we get a graph of z2 against z and in the two-argument case we get a graph of y against z (in this example, the straight line 1:12 vs. 1:12)
par(mfrow=c(1,2)) plotx2(12) plotx2(12,1:12)

You need to specify that the type of plot you want is a line (type="l" using lower-case L, not upper-case I and not number 1) because the default is to produce a scatterplot with open circles as the plotting symbol (type="p"). If you want ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access