7.2 Functions in R

Functions are your loyal servants, waiting patiently to do your bidding to the best of their ability. They’re made with the utmost care and attention … though sometimes may end up being something of a Frankenstein’s monster - with an extra limb or two and a head put on backwards. But no matter how ugly they may be they’re completely faithful to you.

They’re also very stupid.

If we asked you to go to the supermarket to get us some ingredients to make Francesinha, even if you don’t know what the heck that is, you’d be able to guess and bring at least something back. Or you could decide to make something else. Or you could ask a celebrity chef for help. Or you could pull out your phone and search online for what Francesinha is. The point is, even if we didn’t give you enough information to do the task, you’re intelligent enough to, at the very least, try to find a work around.

If instead, we asked our loyal function to do the same, it would listen intently to our request, stand still for a few milliseconds, compose itself, and then start shouting Error: 'data' must be a data frame, or other object .... It would then repeat this every single time we asked it to do the job. The point here, is that code and functions are not intelligent. They cannot find workarounds. It’s totally reliant on you, to tell it very explicitly what it needs to do step by step.

Remember two things: the intelligence of code comes from the coder, not the computer and functions need exact instructions to work.

To prevent functions from being too stupid you must provide the information the function needs in order for it to function. As with the Francesinha example, if we’d supplied a recipe list to the function, it would have managed just fine. We call this “fulfilling an argument”. The vast majority of functions require the user to fulfill at least one argument.

This can be illustrated in the pseudocode below. When we make a function we can specify what arguments the user must fulfill (e.g. argument1 and argument2), as well as what to do once it has this information (expression):

nameOfFunction <- function(argument1, argument2, ...) {expression}

The first thing to note is that we’ve used the function function() to create a new function called nameOfFunction. To walk through the above code; we’re creating a function called nameOfFunction. Within the round brackets we specify what information (i.e. arguments) the function requires to run (as many or as few as needed). These arguments are then passed to the expression part of the function. The expression can be any valid R command or set of R commands and is usually contained between a pair of braces { } (if a function is only one line long you can omit the braces). Once you run the above code, you can then use your new function by typing:

nameOfFunction(argument1, argument2)

Confused? Let’s work through an example to help clear things up.

First we are going to create a data frame called city, where columns porto, aberdeen, nairobi, and genoa are filled with 100 random values drawn from a bag (using the rnorm() function to draw random values from a Normal distribution with mean 0 and standard deviation of 1). We also include a “problem”, for us to solve later, by including 10 NA values within the nairobi column (using rep(NA, 10)).

city <- data.frame(
  porto = rnorm(100),
  aberdeen = rnorm(100),
  nairobi = c(rep(NA, 10), rnorm(90)),
  genoa = rnorm(100)

Let’s say that you want to multiply the values in the variables Porto and Aberdeen and create a new object called porto_aberdeen. We can do this “by hand” using:

porto_aberdeen <- city$porto * city$aberdeen

We’ve now created an object called porto_aberdeen by multiplying the vectors city$porto and city$aberdeen. Simple. If this was all we needed to do, we can stop here. R works with vectors, so doing these kinds of operations in R is actually much simpler than other programming languages, where this type of code might require loops (we say that R is a vectorised language). Something to keep in mind for later is that doing these kinds of operations with loops can be much slower compared to vectorisation.

But what if we want to repeat this multiplication many times? Let’s say we wanted to multiply columns porto and aberdeen, aberdeen and genoa, and nairobi and genoa. In this case we could copy and paste the code, replacing the relevant information.

porto_aberdeen <- city$porto * city$aberdeen
aberdeen_genoa <- city$aberdeen * city$aberdeen
nairobi_genoa <- city$nairobi * city$genoa

While this approach works, it’s easy to make mistakes. In fact, here we’ve “forgotten” to change aberdeen to genoa in the second line of code when copying and pasting. This is where writing a function comes in handy. If we were to write this as a function, there is only one source of potential error (within the function itself) instead of many copy-pasted lines of code (which we also cut down on by using a function).

In this case, we’re using some fairly trivial code where it’s maybe hard to make a genuine mistake. But what if we increased the complexity?

city$porto * city$aberdeen / city$porto + (city$porto * 10^(city$aberdeen)) 
                  - city$aberdeen - (city$porto * sqrt(city$aberdeen + 10))

Now imagine having to copy and paste this three times, and in each case having to change the porto and aberdeen variables (especially if we had to do it more than three times).

What we could do instead is generalise our code for x and y columns instead of naming specific cities. If we did this, we could recycle the x * y code. Whenever we wanted to multiple columns together, we assign a city to either x or y. We’ll assign the multiplication to the objects porto_aberdeen and aberdeen_nairobi so we can come back to them later.

# Assign x and y values
x <- city$porto
y <- city$aberdeen

# Use multiplication code
porto_aberdeen <- x * y

# Assign new x and y values
x <- city$aberdeen
y <- city$nairobi

# Reuse multiplication code
aberdeen_nairobi <- x * y

This is essentially what a function does. OK down to business, let’s call our new function multiply_columns() and define it with two arguments, x and y. In the function code we simply return the value of x * y using the return() function. Using the return() function is not strictly necessary in this example as R will automatically return the value of the last line of code in our function. We include it here to make this explicit.

multiply_columns <- function(x, y) {
  return(x * y)

No that we’ve defined our function we can use it. Let’s use the function to multiple the columns city$porto and city$aberdeen and assign the result to a new object called porto_aberdeen_func

porto_aberdeen_func <- multiply_columns(x = city$porto, y = city$aberdeen)
##   [1] -0.315670416  1.721175970  0.167911743 -0.407278179  0.499532239
##   [6] -0.081989741  0.008005264  1.393384919 -0.018305482 -2.009931673
##  [11]  0.040163627  0.653042800  0.004186977  0.764812035  0.144654474
##  [16]  0.587719216  0.350954935  1.596679403 -0.490790705 -0.057377261
##  [21]  0.257268469  0.615264841 -0.221134743 -0.034221228  2.545779226
##  [26] -0.159416710  0.094911398  0.282645862  0.497404197 -0.078187984
##  [31] -0.003566018  0.038834992  1.850158591 -0.022146003 -0.076286074
##  [36]  0.081143183 -0.115940682 -1.111923834  0.632789027  1.231849588
##  [41] -0.583089886 -2.130598785  0.827693233  0.237400461  1.780521629
##  [46]  0.212951086 -0.392843639 -4.293254813  0.409623937 -1.992127507
##  [51] -3.072313811 -0.285388211 -1.153962106 -1.142402674 -0.337029044
##  [56]  0.514314955  0.194525938 -0.004077411 -0.372055223  1.942244207
##  [61] -0.052910585  0.396978212  1.099961299 -0.554456138  2.634420371
##  [66] -0.401551612  2.828971355  2.078878518  0.019762448 -0.205883975
##  [71] -0.502233084  0.088694158 -1.480859634  2.424316587 -2.156276235
##  [76]  0.221843094 -0.228743883  0.177872505 -0.511497586  0.083603954
##  [81] -2.552364151  0.012183294 -0.504080171 -0.131989485  0.529768829
##  [86]  0.603672257  0.592229677  1.212047664 -3.339425000  0.598922634
##  [91] -0.805267411  0.012647554 -0.436599721 -0.066224721  0.097092542
##  [96]  0.092353781  0.010941260  0.062777972 -0.092227108  2.677943152

If we’re only interested in multiplying city$porto and city$aberdeen, it would be overkill to create a function to do something once. However, the benefit of creating a function is that we now have that function added to our environment which we can use as often as we like. We also have the code to create the function, meaning we can use it in completely new projects, reducing the amount of code that has to be written (and retested) from scratch each time. As a rule of thumb, you should consider writing a function whenever you’ve copied and pasted a block of code more than twice.

To satisfy ourselves that the function has worked properly, we can compare the porto_aberdeen variable with our new variable porto_aberdeen_func using the identical() function. The identical() function tests whether two objects are exactly identical and returns either a TRUE or FALSE value. Use ?identical if you want to know more about this function.

identical(porto_aberdeen, porto_aberdeen_func)
## [1] TRUE

And we confirm that the function has produced the same result as when we do the calculation manually. We recommend getting into a habit of checking that the function you’ve created works the way you think it has.

Now let’s use our multiply_columns() function to multiply columns aberdeen and nairobi. Notice now that argument x is given the value city$aberdeenand y the value city$nairobi.

aberdeen_nairobi_func <- multiply_columns(x = city$aberdeen, y = city$nairobi)
##   [1]           NA           NA           NA           NA           NA
##   [6]           NA           NA           NA           NA           NA
##  [11]  0.014343912 -0.269947054 -0.016726710  0.847463585 -0.556615835
##  [16]  0.710904826 -2.679353712  2.098969590  0.103279335  0.272201325
##  [21] -0.100471908 -0.332258286  0.171987616 -0.583842393  0.437984593
##  [26]  0.310633691 -0.260902667 -0.432362455  0.401464284  0.618283734
##  [31] -1.033872079 -0.386920334  1.894545619  0.007224255 -0.040881436
##  [36] -0.200920262 -0.080400341 -0.938793088  0.156444718  1.074148132
##  [41] -0.419231006  2.115975127  0.609182320 -0.193378693 -0.797598603
##  [46]  0.769334330  0.391860050  0.110918007 -0.211714482  2.819469961
##  [51] -1.571249345 -0.642368027 -0.750647483 -0.970555425 -0.181471747
##  [56] -3.960187334 -0.528061113  0.317486839  0.071072997  1.869834303
##  [61] -0.133641416 -0.458717931 -0.120824756  1.622472467  0.448236080
##  [66]  0.217232837  1.683585263 -3.052791514  0.093282777 -0.085112366
##  [71] -0.122654838 -4.293452554 -0.655311925  1.093551283  0.122321093
##  [76] -0.110150576  0.297978935  0.283829276  0.046371126 -0.102694462
##  [81] -1.950929143 -0.035686474 -0.970671597 -0.249168071  1.081296387
##  [86]  1.776303921  1.659055505 -3.683319523 -1.479610453 -0.014241121
##  [91]  0.575898494  0.002014276  0.008307122  0.031705628 -0.254238534
##  [96] -0.810250089 -0.008233265 -0.073561111 -1.257869958  0.451169072

So far so good. All we’ve really done is wrapped the code x * y into a function, where we ask the user to specify what their x and y variables are.

Now let’s add a little complexity. If you look at the output of nairobi_genoa some of the calculations have produced NA values. This is because of those NA values we included in nairobi when we created the city data frame. Despite these NA values, the function appeared to have worked but it gave us no indication that there might be a problem. In such cases we may prefer if it had warned us that something was wrong. How can we get the function to let us know when NA values are produced? Here’s one way.

multiply_columns <- function(x, y) {
  temp_var <- x * y
  if (any(is.na(temp_var))) {
    warning("The function has produced NAs")
  } else {

aberdeen_nairobi_func <- multiply_columns(city$aberdeen, city$nairobi)
## Warning in multiply_columns(city$aberdeen, city$nairobi): The function has
## produced NAs
porto_aberdeen_func <- multiply_columns(city$porto, city$aberdeen)

The core of our function is still the same. We still have x * y, but we’ve now got an extra six lines of code. Namely, we’ve included some conditional statements, if and else, to test whether any NAs have been produced and if they have we display a warning message to the user. The next section of this Chapter will explain how these work and how to use them.