Creating Functions


Teaching: 60 min
Exercises: 30 min
  • How do I make a function?

  • How can I test my functions manually?

  • How should I document my code?

  • Define a function that takes arguments.

  • Return a value from a function.

  • Test a function manually.

  • Set default values for function arguments.

  • Explain why we should divide programs into small, single-purpose functions.

  • Write documentation comments that can be automatically compiled to R’s native help and documentation format.

If we only have one data set to analyze, it would probably be faster to load the file into a spreadsheet and use that to plot some simple statistics. However, we often have multiple data files or can expect more in the future. That’s why it’s usually a good idea to prepare for this case and write code in a reproducible manner right away. In this lesson, we’ll learn how to write a function so that we can repeat several operations with a single command.

Defining functions

Let’s start by defining a function fahrenheit_to_kelvin that converts temperatures from Fahrenheit to Kelvin:

fahrenheit_to_kelvin <- function(temp_F) {
  temp_K <- ((temp_F - 32) * (5 / 9)) + 273.15

We define fahrenheit_to_kelvin by assigning it to the output of function. The arguments are listed within parentheses. In this case, it’s only one. Next, the body of the function (i.e. the statements that are executed when it runs) is surrounded by { curly braces }. The statements in the body are indented by two spaces, which makes the code easier to read but does not affect how the code operates.

When we call the function, the values we pass to it are assigned to those variables so that we can use them inside the function. Inside the function, we use a return statement to send a result back to whoever asked for it.

Automatic Returns

In R, it is not necessary to include the return statement. R automatically returns the return value of last line of the body of the function. While in the learning phase, we will explicitly define the return statement.

Let’s try running our function. Calling our own function is no different from calling any other function:

# freezing point of water
[1] 273.15
# boiling point of water
[1] 373.15

We’ve successfully called the function that we defined, and we have access to the value that we returned.

Composing functions

Now that we’ve seen how to turn Fahrenheit into Kelvin, it’s easy to turn Kelvin into Celsius:

kelvin_to_celsius <- function(temp_K) {
  temp_C <- temp_K - 273.15

# absolute zero in Celsius
[1] -273.15

What about converting Fahrenheit to Celsius? We could write out the formula, but we don’t need to. Instead, we can compose a third function from our two previous ones:

fahrenheit_to_celsius <- function(temp_F) {
  temp_K <- fahrenheit_to_kelvin(temp_F)
  temp_C <- kelvin_to_celsius(temp_K)

# freezing point of water in Celsius
[1] 0

This is our first taste of how larger programs are built: we define basic operations, then combine them in ever-larger chunks to get the effect we want. Real-life functions will usually be larger than the ones shown here: typically half a dozen to a few dozen lines. However, they shouldn’t ever be much longer than that, or the next person who reads them won’t be able to understand what’s going on.

Nesting Functions

The previous example showed the output of fahrenheit_to_kelvin assigned to temp_K, which is then passed to kelvin_to_celsius to get the final result. It is also possible to perform this calculation in one line of code, by “nesting” one function inside another, like so:

# freezing point of water in Celsius
[1] 0

Create a Function

R has a built-in function to combine elements into a vector: the c function. E.g. x <- c("A", "B", "C") creates a vector x with three elements. Furthermore, we can extend that vector again using c, e.g. y <- c(x, "D") creates a vector y with four elements. Write a function called wrapper that takes two vectors as arguments, called original and highlight, and returns a new vector that has the highlighting at the beginning and end of the original:

best_practice <- c("Write", "programs", "for", "people", "not", "computers")
dry_principle <- c("Don't", "repeat", "yourself", "or", "others")
asterisk <- "***"  # R interprets a variable with a single value as a vector
                   # with one element.
wrapper(best_practice, asterisk)
[1] "***"       "Write"     "programs"  "for"       "people"    "not"      
[7] "computers" "***"      
wrapper(dry_principle, asterisk)
[1] "***"      "Don't"    "repeat"   "yourself" "or"       "others"  
[7] "***"     


wrapper <- function(original, highlight) {
  answer <- c(highlight, original, highlight)

The Call Stack

For a deeper understanding of how functions work, you’ll need to learn how they create their own environments and call other functions. Function calls are managed via the call stack. For more details on the call stack, have a look at the supplementary material.

Named Variables and the Scope of Variables

Functions can accept arguments explicitly assigned to a variable name in the function call functionName(variable = value), as well as arguments by order:

input_1 <- 20
mySum <- function(input_1, input_2 = 10) {
  output <- input_1 + input_2
  1. Given the above code was run, which value does mySum(input_1 = 1, 3) produce?
    1. 4
    2. 11
    3. 23
    4. 30
  2. If mySum(3) returns 13, why does mySum(input_2 = 3) return an error?

Testing functions interactively

Once we start putting things in functions so that we can re-use them, we need to start testing that those functions are working correctly. To see how to do this, let’s write a function to center a dataset around a particular value. Please create a new file for this and save it as center.R.

center <- function(data, desired) {
  new_data <- (data - mean(data)) + desired

We could test this on our actual data, but since we don’t know what the values ought to be, it will be hard to tell if the result was correct. Instead, let’s create a small vector of integers and center it around a small integer, so that we can comprehend, retrace and therefore check the calculation in our head:

(z <- c(1, 2, 3))
[1] 1 2 3
center(z, 3)
[1] 2 3 4

That looks right, so let’s try centering our inflammation data from day 4 around 0:

dat <- read.csv(file = "inflammation.csv", header = FALSE)
centered <- center(dat[, 4], 0)
[1]  1.25 -0.75  1.25 -1.75  1.25  0.25

It’s hard to tell from the default output whether the result is correct, but there is one test that will reassure us: the standard deviation hasn’t changed.

# original standard deviation
sd(dat[, 4])
[1] 1.067628
# centered standard deviation
[1] 1.067628

Those values look the same, but we probably wouldn’t notice if they were different in the sixth decimal place. Let’s do this instead:

# difference in standard deviations before and after
sd(dat[, 4]) - sd(centered)
[1] 0

Sometimes, a very small difference can be detected due to rounding at very low decimal places. R has a useful function for comparing two objects allowing for rounding errors, all.equal:

all.equal(sd(dat[, 4]), sd(centered))
[1] TRUE

It’s still possible that our function is wrong, but it seems unlikely enough that we should probably get back to doing our analysis. We have one more task first, though: we should write some documentation for our function to remind ourselves later what it’s for and how to use it.

Documenting functions

A common way to put documentation in software is to add “informal” comments like this:

center <- function(data, desired) {
  # return a new vector containing the original data centered around the
  # desired value.
  # Example: center(c(1, 2, 3), 0) should return [1] -1  0  1
  new_data <- (data - mean(data)) + desired

This is a good practice to begin with. Keeping the documentation exactly next to the code helps keeping the former in sync with code changes. However, when using ?… or help(…) we do not see such informal comments.

How can we create conveniently readable help pages for our own functions? By using the roxygen2 package!


It can convert “formal” documentation comments (lines starting with #') into the standard R format for help pages. You will learn more about taking advantage of this conversion in the packaging episode.

Technical details of R’s help page format

Help pages are rendered not directly from the roxygen comments, but from .Rd files that use a markup language similar to LaTeX. roxygen2 generates those .Rd files from the formal function documentation comments. Therefore, R coders don’t have to write these LaTeX-like files separately, but instead document their functions alongside the code.

For now, let’s prepare a solid foundation of using roxygen2’s #' notation for documenting functions. Please compare the following to the informal comments we used above and in the “Analyzing Patient Data” episode:

#' Centering Data
#' @param data The numeric vector to be centered
#' @param desired The numeric value around which the data will be centered
#' @return A new vector containing the original data centered around the desired value.
#' @export
#' @examples
#'   center(c(1, 2, 3), 0)  # should return [1] -1  0  1
center <- function(data, desired) {
  new_data <- (data - mean(data)) + desired

Unsurprisingly, the first line should be a short, descriptive title. Additional text paragraphs are possible after leaving one line blank with only a #'. The descriptive tags (preceded by an @) hold the most important details. Each @param documents an input parameter, while @return explains the function’s output. The more comprehensible a description of its in- and output data (types), the easier a function can be integrated into larger analysis pipelines. @export means that the function is presented to users, after we have packaged it in a later episode.

Functions to Create Graphs

To automate the plotting of the graphs from the previous lesson (average inflammation over time), we wrote the following function:

analyze <- function(filename) {
  # Input a character string that correspondes to a filename to 
  # to get the average inflammation of each day plotted.  
  dat <- read.csv(file = filename, header = FALSE)
  avg_day_inflammation <- colMeans(dat)

Formalise the above comments into roxygen-style function documentation.


#' Analyse One of My Patient Inflammation Data Files
#' @param filename character string of a .csv file
#' @return Plots the average inflammation over time.
#' @export
#' @examples 
#'   analyze("inflammation.csv")
analyze <- function(filename) { … }

If you are using RStudio, a nice shortcut is Ctrl+Shift+Alt+R. Place the cursor inside the function name or body, press that shortcut, and a roxygen comment skeleton will be inserted.


Another example of an informally documented function:

rescale <- function(v) {
  # takes a vector as input
  # returns a corresponding vector of values scaled to the range 0 to 1
  # e.g.: rescale(c(1, 2, 3)) => 0.0 0.5 1.0
  L <- min(v)
  H <- max(v)
  result <- (v - L) / (H - L)

Please create a new file for this and save it as rescale.R, and test that it is mathematically correct by using min, max, and plot.

Rescaling documentation

Convert rescale’s comments into roxygen function docu! Which keyboard shortcut gets you started in RStudio?


Find the keyboard shortcut above, and one possible roxygen documentation below.

#' Rescaling vectors to lie in the range 0 to 1
#' @param v A numeric vector
#' @return The rescaled numeric vector
#' @export
#' @examples
#'   rescale(c(1, 2, 3))  # should return [1] 0.0 0.5 1.0
#'   rescale(c(1, 2, 3, 4, 5))  # should return [1] 0.00 0.25 0.50 0.75 1.00
rescale <- function(v) { ... }

Defining defaults

We have passed arguments to functions in two ways: directly, as in dim(dat), and by name, as in read.csv(file = "inflammation.csv", header = FALSE). In fact, we can pass the arguments to read.csv without naming them:

dat <- read.csv("inflammation.csv", FALSE)

However, the position of the arguments matters if they are not named.

dat <- read.csv(header = FALSE, file = "inflammation.csv")
dat <- read.csv(FALSE, "inflammation.csv")
Error in read.table(file = file, header = header, sep = sep, quote = quote, : 'file' must be a character string or connection

To understand what’s going on, and make our own functions easier to use, let’s save our center.R file as center2.R and re-define the function as follows.

#' Centering Data
#' @param data The numeric vector to be centered
#' @param desired The numeric value around which the data should be centered (default = 0)
#' @return A new vector containing the original data centered around the desired value.
#' @export
#' @examples
#'   center2(c(1, 2, 3))  # should return [1] -1  0  1
#'   center2(c(1, 2, 3), 1)  # should return [1] 0 1 2
center2 <- function(data, desired = 0) {
  new_data <- (data - mean(data)) + desired

The key change is that the second argument is now written desired = 0 instead of just desired. If we call the function with two arguments, it works as it did before:

test_data <- c(1, 2, 3)
center2(test_data, 3)
[1] 2 3 4

But we can also now call center2() with its first argument only, in which case desired is automatically assigned the default value of 0:

(more_data <- 5 + test_data)
[1] 6 7 8
[1] -1  0  1

This is handy: if we usually want a function to work one way, but occasionally need it to do something else, we can allow people to pass an argument when they need to but provide a default to make the normal case easier.

Matching Arguments

To be precise, R has three ways that arguments supplied by you are matched to the formal arguments of the function definition:

  1. by complete name,
  2. by partial name (matching on initial n characters of the argument name), and
  3. by position.

Arguments are matched in the manner outlined above in that order: by complete name, then by partial matching of names, and finally by position.

A Function with Default Argument Values

Save the rescale function as rescale2.R and rewrite it to scale a vector to lie between 0 and 1 by default, but will allow the caller to specify lower and upper bounds if they want. Compare your implementation to your neighbor’s: do the two functions always behave the same way?


#' Rescaling Vectors To Lie In A Lower- And Upper-Bounded Range
#' @param v A numeric vector
#' @param lower numeric (default = 0)
#' @param upper numeric (default = 1)
#' @return The rescaled numeric vector
#' @export
#' @examples
#'   rescale2(c(1, 2, 3))  # should return [1] 0.0 0.5 1.0
#'   rescale2(c(1, 2, 3), 1, 2)  # should return [1] 1.0 1.5 2.0
rescale2 <- function(v, lower = 0, upper = 1) {
  L <- min(v)
  H <- max(v)
  result <- (v - L) / (H - L) * (upper - lower) + lower
rescale2(v = dat[, 4], lower = 2, upper = 5))
rescale2(dat[, 4], -5, -2))
Error: <text>:1:45: unexpected ')'
1: rescale2(v = dat[, 4], lower = 2, upper = 5))

Compare both rescale2 calls: Which is more understandable? Although passing arguments purely by position is very convenient, because you have to type less, it’s usually better to write the argument name. Most code is more often read, than edited, so the reader (maybe your future self) may loose more time understanding the code (e.g. by having to look up non-obvious details) than you saved by typing less. Also, a good IDE (integrated development environment) will reduce your typing with auto-completion. Thus, it is generally better to only omit an argument name if its value clarifies it. For example, read.csv("path/to/") is comprehensible even without ...(file = "... in the middle.

Key Points

  • Define a function using name <- function(...arguments...) {...body...}.

  • Specify default values for arguments when defining a function using name = value in the argument list.

  • Call a function using name(arg1 = value, ...).

  • R looks for variables in the current stack frame before looking for them at the top level.

  • Make code more readable by passing arguments preferably by name.

  • Arguments can be passed by matching based on name, by position, or by omitting them (in which case the default value is used).

  • Use ?name or ??name to find the help page of a function.

  • Write formal roxygen2 comments for your functions and generate help pages from those.