Optional Arguments

Here is a function called charplot that produces a scatterplot of x and y using solid red circles as the plotting symbols: there are two essential arguments (x and y) and two optional (pc and co) to control selection of the plotting symbol and its colour:

charplot<-function(x,y,pc=16,co="red"){
plot(y~x,pch=pc,col=co)}

The optional arguments are given their default values using = in the argument list. To execute the function you need only provide the vectors of x and y,

charplot(1:10,1:10)

to get solid red circles. You can get a different plotting symbol simply by adding a third argument

charplot(1:10,1:10,17)

which produces red solid triangles (pch=17). If you want to change only the colour (the fourth argument) then you have to specify the variable name because the optional arguments would not then be presented in sequence. So, for navy-coloured solid circles, you put

charplot(1:10,1:10,co="navy")

To change both the plotting symbol and the colour you do not need to specify the variable names, so long as the plotting symbol is the third argument and the colour is the fourth

charplot(1:10,1:10,15,"green")

which produces solid green squares. Reversing the optional arguments does not work

charplot(1:10,1:10,"green",15)

(this uses the letter g as the plotting symbol and colour no. 15). If you specify both variable names, then the order does not matter:

charplot(1:10,1:10,co="green",pc=15)

This produces solid green squares despite the arguments being ...

Get The R Book now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.