Functions! (and their scoping)

r-tutorials
scripting-tutorials
machine-learning
Published

May 9, 2016

In a previous post, we covered part of the R language control flow, the cycles or loop structures. In a subsequent one, we showed how to avoid ‘looping’ by means of functions that act on compound data in repetitive ways (the apply family of functions). Here, we introduce the notion of function from the R programmer point of view and illustrate the range of action that functions have within the R code (‘scope’).

Functions normally take some data as input and give a result as an output. In some programming languages, to save the result of a function as a variable, you need to explicitly include a return statement at the end of the function body. This is not the case in R, which will always return a value that can be stored in a variable — however, for readability, it’s good practice to include return explicitly when defining a function:

mean_two_numbers <- function(num_1, num_2) { # with return
  mean <- (num_1 + num_2) / 2
  return(mean)
}

mean_two_numbers_2 <- function(num_1, num_2) { # without return
  mean <- (num_1 + num_2) / 2
  mean
}

If a function should return multiple values, store them in a list and include the list in the return.

Note

This post originally continued on DataCamp with a fuller discussion of function scope; that page has since gone offline, and only the fragment above was recoverable. If you have the original source, this section can be completed — otherwise it stays as-is.

First published on DataCamp, August 20, 2015.