An AWESOME feature of R, and perhaps a main reason for using it, is that it allows you to program your own functions. In fact, all the commands that you use in R are functions.

We can look at the basic structure of a function in R by typing the function name, but excluding the parentheses. For example, lets take a look at the function for taking the row mean of an object, rowMeans(). Just type:

rowMeans # There is a lot going on, but you see the structure.

The basic structure of a function is: <- function(arguments or things you need separated by commas){
actions or stuff you want the function to be doing
return(information you want from the function)

Basically, we are passing in an object or objects, doing something to it, and then returning an output.

For example, let’s create a function that calculates the mean of a variable:

function.mean <- function(input){
  our.mean <- sum(input)/length(input) 

This function takes an object input and divides the sum of input by the length of input and returns this ratio as an object called our.mean. Note that the names we use for the objects are arbitrary.

The function reads as: create a function called function.mean, this function takes one argument called input, the function will create an object called our.mean by summing input and dividing it by the length of input, the function then returns the object our.mean.

Remember that we can see our function by just typing the name function.mean.

Now, let’s create an object called x and calculate the mean using our function:

x <- c(1,2,3,4,5)
## [1] 3
x.mean <- function.mean(x)
## [1] 3

Note here that x is the input in the function. Also, note that we can use the function we created to make an object. The command: function.mean(x) just returns the mean, but the command: x.mean <- function.mean(x) creates the object x.mean that is the mean of the object x.

Commenting inside the function is helpful for keeping track of what is going on, as well as for others who might want to use a function you have created. In R, any line with a # sign in front is commented out of the code in the