R Programming/Working with functions

Looking at the code of a function

 * You can type the name of the function in the console without any round brackets after the name. This will print the code of the function in the console.
 * You can also use the  function which opens a new editor window and prints the code of the function in this editor.
 * You can also use the  function in the TinnR package to copy the code of the function. Then you just have to paste it in a text editor to have a look at it.

Here is an example with the  function.

Returning an object
By default the value of the last line (*) is returned. In the following example, we have a simple function with two objects. The last one is returned.

The function can return an object explicitly using return (but as it is the last line, you could simply use x instead):


 * ) More precisely, it is not the "last line" but rather the value of the last evaluation which is returned from the function.

Adding arguments
It is possible to add arguments.

Note that the above function would rather be written (and be more efficient) as (as the last value is returned)

The  argument means that you can add other arguments which will be passed to functions inside the function.

It is possible to add a dataframe as argument. Here is an example :

For estimation commands it is possible to add formulas as arguments. For instance, we can create our own function for ordinary least square using a formula interface.

Recursive functions
R supports recursive functions. The function below computes Fibonacci numbers recursively.

Functions as Objects
R functions can be treated as objects This can be useful when wanting to make many different kinds of functions

Higher-order functions
You can use higher-order functions in R. Contrary to common belief, using them instead of loops, is not faster, because the apply function has a for-loop inside its definition. Use them only to improve clarity of your code.

apply
apply is the most basic of R's map functions. lapply, sapply and mapply are convenient interfaces for apply that work on lists, vectors and multiple vectors respectively.

apply takes as arguments an array, a vector of the dimension to map along and a function. The following example is based on the apply documentation. It uses apply to compute column and row sums of a matrix.

tapply
tapply is similar to apply, but applies a function to each cell of a ragged array, that is to each (non-empty) group of values given by a unique combination of the levels of certain factors.

Reduce
This function from the Reduce documentation cumulatively adds