Writing functions in R
Although R has many built-in functions that will perform a wide variety of tasks, sooner or later most R users will want to write their own functions in R. Essentially a function is just a small program that produces a defined output given a specified input. To take a very simple example, supposed we want to write our own function to compute the sample mean. We do this by writing a new object called (for example) my_mean, which is now a function.
my_mean<-function(x){sum(x)/length(x)}
The input to the function is a list of numbers x, and the function computes the mean by first computing the sum and then dividing by the number of elements (both from built-in functions). Notice that if we simply type the function on the input line (or input it from script) we just get the function description
> my_mean
function(x){sum(x)/length(x)}
To actually use the function we must provide inputs (x), so a list of numbers. For example,
> data<-c(1,2,3,4,5,5,6)
> my_mean(data)
[1] 3.714286
>
applies the value of a list (“data”) to the function and returns the mean.
More complex functions can be written that involve 2 or more inputs. For example the function
> my_fun<-function(x,y){x*2+log(y)}
produces the function
You can confirm that the function produces correct results for sample data by performing these same calculations on a calculator, e.g.,
> my_fun(2,3)
[1] 5.098612
> 2*2+log(3)
Although the above examples seem somewhat trivial-- because they are-- the idea is readily extended to more important and useful applications. Examples we will see later include;
Functions to convert data from a file, data base, or other format to a format compatible with a program for CMR analysis (MARK, RMark)
Functions to convert from one scale or set of measurement units to another (e.g., see the temperature conversion example)
Functions to run a set of models on a data set and summarize the results (include plotting)
Functions to simulate data under a specific model and then run the simulated data though an estimation program
Next: Review Exercises