Writing functions

R has many ready to use functions to calculate statistics and to make plots. R packages contain further functions which have been written by contributors to perform more specialised analyses.

In this lesson you will learn how to write your own function in R.

To write your own function you will need specify:

The general syntax in R appears as follows:

function_name <- function(inputs) {
  calculation / operation
  return(outputs)
}

Let’s start by writing a function which calculates the mean of a vector of numbers. In this case we have the following:

To set up our function, we assign our function name mean_fun using

mean_fun <- function(x) {
  n <- length(x)
  result <- sum(x) / n
  return(result)
}

We run the above lines to load our function into our environment. Then we can use our new function with any vector x.

x <- c(4, 5, 6, 3, 3, 2, 2, 4, 5, 1)
mean_fun(x)
[1] 3.5

We can extend our function to return more than one output. As well as returning the mean value, we also want to return n. Therefore we specify a list of outputs to return.

mean_fun <- function(x) {
  n <- length(x)
  result <- sum(x) / n
  return(list(result, n))
}

Now let’s run it again,

x <- c(4, 5, 6, 3, 3, 2, 2, 4, 5, 1)
mean_fun(x)
[[1]]
[1] 3.5

[[2]]
[1] 10

We can extend this even further by naming the outputs in our list.

mean_fun <- function(x) {
  n <- length(x)
  result <- sum(x) / n
  return(list(mean_val = result, n = n))
}

Then we assign the output to my_result and we can extract the mean using mean_val or the number of observations using n.

x <- c(4, 5, 6, 3, 3, 2, 2, 4, 5, 1)
my_result <- mean_fun(x)
my_result$mean_val
[1] 3.5
my_result$n
[1] 10