Functions
Functions are another kind of object in R (which means they behave like other objects in R, including that they can be passed as arguments to other functions). As with most computing languages, most work is done through functions, both built-in and user defined. You can get an unsorted (very long, containing around 4000 items) list of built-in functions via the function ; remember that you can then query the documentation for promising candidates using
. Appendix D of the R user manual also has an alphabetized list with page references that illustrate their use.
You can also write your own functions. Since R has so many functions, it is good practice to make sure your function names (or variable names) are not already being used. The easiest way to check this is to type the name of the proposed function or name. You will either get back an error message saying the object is not found or a definition of the function.
As an example, we will construct a simple function which will sum the contents of a vector given to it. The +
characters represent line continuation in R. They will appear automatically when you press return after typing the preceding line. They are not part of the function definition code and you should not type them.
The return value can be any type of object. Here we return a vector:
Default arguments can be defined for functions:
Note that when an argument with a default value is omitted, the default value is passed into the function; also observe that the arguments can be passed positionally or by name; in many cases, code is more readable if values are passed by name.
There can be some variability in the arguments which can be accepted by a function, using the ("three-dots" or "ellipsis") argument. Consider the combine function,
, the argument list of which we can see by simply typing its name at the console prompt (note that this won't work if you have also defined a variable called
, as that will be displayed instead. If so, you can remove it from your workspace with
):
Here, the three-dots argument allows a list of arguments, which are not specified in advance and which will be combined into a vector or list. We could write an equivalent of our function which just takes an arbitrary number of numerical arguments, which can either be passed directly to another function—a common use for
—or which can be turned into a vector or other object:
Alternatively, instead of using , we could use
to generate a quantity through which we can iterate: