Contents
 
Introduction
To R

The Formal Form of Functions...

Arguments

I've not really gone into detail about the way R calls functions. Time to do that.

When you call a function in R, you have the function name, and then the argument list in parentheses (round brackets like these). The argument list is a comma-separated list of arguments. Arguments may be unnamed, named, or missing. I'll use the seq() function to illustrate this.

We've used seq() with three arguments to generate a sequence:

> seq(1,27,3)
[1]  1  4  7 10 13 16 19 22 25
These are three unnamed arguments. We could also use the named arguments form:
> seq(from=1,to=27,by=3)
[1]  1  4  7 10 13 16 19 22 25
Notice how each argument is preceded by "name=". But what is the point of that, since it just means more typing? Two reasons - first the code is a bit more readable, since we then have a clue as to what the arguments mean, and secondly some functions will do different things if given different named arguments.

For example, the seq() function can generate a sequence of a given length if given the length= named argument:

> seq(from=1,to=27,length=4)
[1]  1.000000  9.666667 18.333333 27.000000
This returns a sequence that starts and ends at the from and to values, of length 4, and computes the required by value itself (here its 8.6667).

Argument names can be abbreviated as long as they are still uniquely identified within the set of possible names. The above example could be written seq(f=1,t=27,l=4) and the position of named arguments is fairly irrelevant - you could also have written seq(t=27,l=4,f=1) if you wanted to.

If arguments are left out they are called missing. If the function has a default value for a missing argument then this is an optional argument, otherwise its a required argument and the function produces an error message:

> seq(1,4)   missing by defaults to 1
[1] 1 2 3 4
> seq(4)     missing from defaults to 1
[1] 1 2 3 4
> seq()      missing everything defaults to 1!!
[1] 1
R will often have sensible defaults for most arguments, but I'm sure I can find an example...
> sqrt()
Error: 0 arguments passed to "sqrt" which requires 1.

Contents