Writing Functions

Writing custom functions is a great way to encapsulate code that you want to re-use

A function has one way in and one way out

example <- function() {
  ## do something useful here
  return()
}
example()

Anatomy of a Function

Functions have:

  • a name
  • 0 or more arguments
  • the body of the function (i.e., code that does something with the arguments)
  • a return value

Anatomy of a Function

isItADuck <- function(input){
  test <- input == "duck"
  return(test)
}
  • isItADuck = the name of the function
  • input = the only argument for this function
  • all the code between the curly brackets {} is the body of the function
  • we use return() to specify what gets returned when we call the function (in this case it will be TRUE or FALSE, because we are returning the result of a logical test)

Anatomy of a Function

isItADuck <- function(input){
  test <- input == "duck"
  return(test)
}
  1. the names input and test do not exist outside the function (i.e. after running the above code, you will get the following error if you type input into the R interpreter) Error in eval(expr, envir, enclos) : object 'input' not found

  2. Nothing happens when we create the function. Stuff happens later when we call the function with specific arguments.

Asking a function to run

isItADuck <- function(input){
  test <- input == "duck" 
  return(test)
}

I assume you ran the code above in R (i.e. you defined our function)

Now we can call the function with a specified value for our argument.

isItADuck("cat")
## [1] FALSE

Asking a function to run

isItADuck("cat")
## [1] FALSE
  • When we ask isItADuck() to run, it needs an argument called input. But remember, this value this doesn’t exist outside the function.

  • We solved this problem by providing "cat" as the value of input.

Asking a function to run

isItADuck("cat")
## [1] FALSE
  • Our function took an argument, determined whether or not it was a duck, and returned either TRUE or FALSE

  • Now we can re-use this function over and over

Running a function over and over

animals <- c("cat", "dog", "duck", "chicken")
for(animal in animals){
  print(isItADuck(animal))
}
## [1] FALSE
## [1] FALSE
## [1] TRUE
## [1] FALSE

more examples

makeSound <- function(sound) {
  #don't forget to install the beepr package
  library(beepr)
  beep(sound)
  return(paste("I beeped sound number", sound))
}

makeSound(5)
x <- makeSound(7)
x

for(i in 1:11) {
  makeSound(i)
  Sys.sleep(1)
}

Summary

A function has arguments, that can only be referenced within the function itself.

When you ask a function to run, you must provide values for these arguments

Code within the body of the function gets run

A single value is returned