Writing Functions

As we have seen, R comes with many useful functions, and still more functions are available by way of R libraries. However, we will often by interested in performing an operation for which no function is available.

Creating a Function

In cases where there are no pre-existing functions that suit our needs, we may want to write our own function. For instance, below we provide a simple function that reads in the ISLR2 and MASS libraries, called LoadLibraries(). Before we have created the function, R returns an error if we try to call it.

LoadLibraries
Error in eval(expr, envir, enclos): object 'LoadLibraries' not found
LoadLibraries()
Error in LoadLibraries(): could not find function "LoadLibraries"

Now, if we create the function using the function() call in R, both LoadLibraries and LoadLibraries() should be able to work.

If you’re writing code in the R terminal, note that the + symbols are printed by R and should not be manually typed in. The { symbol informs R that multiple commands are about to be input. Hitting Enter after typing { will cause R to print the + symbol. This allows us to input as many commands as we wish, hitting Enter after each one. Finally, the } symbol informs R that no further commands will be entered.

LoadLibraries <- function() {
    library(ISLR2)
    library(MASS)
    print("The libraries have been loaded.")
}

To test, let’s retry what we initially typed in:

LoadLibraries
function() {
    library(ISLR2)
    library(MASS)
    print("The libraries have been loaded.")
}
LoadLibraries()
[1] "The libraries have been loaded."

Homemade Function Example

For this example, let us write a function that outputs the five-number summary, alongside the mean and standard deviation given a vector of data points.

FindNumbers <-  function(x){
  # Input: x, is a vector of data, eg. x=c(1,3,10,32,13,21,5,16)
  # Output: five-number, mean, standard deviation
  fnum = fivenum(x)
  names(fnum) = c("Min","Q1", "Median","Q3","Max")
  xbar = mean(x)
  std = sd(x)
  return( c(fnum, Mean=xbar,std=std))
}

To test, let us create a vector of numbers and compare them to the base-R functions mean(), sd(), and fivenum().

y = c(10,14,16,18,20,22,24,28) # Test vector

mean(y)
[1] 19
sd(y)
[1] 5.756983
fivenum(y)
[1] 10 15 19 23 28

In comparison, the output of our homemade function, FindNumbers(), returns the same values successfully:

FindNumbers(y)
      Min        Q1    Median        Q3       Max      Mean       std 
10.000000 15.000000 19.000000 23.000000 28.000000 19.000000  5.756983