What and how?

What is a function?

input --> function does something --> output
  • Main benefit: Avoid repetition.

  • When you write code you should aim for laziness.
    • If you are about to copy a piece of code 5 times and just change a variable in each instance, you are better off converting it into a function.
    • In general, never repeat yourself when you write code, it's called the DRY (Don't Repeat Yourself) principle.
  • Another advantage: Self contained code such that any variable you create inside a function will not be exported into your global environment.

How to write functions in R?

## Fahrenheit to Celsius
(70 - 32) * 5/9
## [1] 21.11111
(65 - 32) * 5/9
## [1] 18.33333
(85 - 32) * 5/9
## [1] 29.44444

Let's convert this into a function:

fahr_to_celsius <- function(temp) {
    (temp - 32) * 5/9
}

Don't forget to re-evaluate your function, after modifying it.

A little better:

convert_fahr <- function(temp, to) {
    res <- (temp - 32) * 5/9
    if (to == "kelvin") {
        res <- res + 273.15
    }
    res
}

Making your functions more versatile and robust

Control the format of input

With functions you can easily control the format of the input and avoid the chances for typos or other small mistakes.

convert_fahr <- function(temp, to = c("celsius", "kelvin")) {
    to <- tolower(to)
    to <- match.arg(to)
    res <- (temp - 32) * 5/9
    if (to == "kelvin") {
        res <- res + 273.15
    }
    res
}

Make your functions expendable

Let's refactor this function into something even better that will allow you to easily expend the convert_fahr function to other units:

fahr_to_celsius <- function(temp) {
    (temp - 32) * 5/9
}

celsius_to_kelvin <- function(temp) {
    temp + 273.15
}

convert_fahr <- function(temp, to = c("celsius", "kelvin")) {
    to <- tolower(to)
    to <- match.arg(to)
    res <- fahr_to_celsius(temp)
    if (to == "kelvin") {
        res <- celsius_to_kelvin(res)
    }
    res
}

Your intentions are clear, everything is self contained, you can easily debug, test and document each of the steps involved.

Your turn!

Challenge

Write a function that converts pounds in kilograms (divides by 2.2).

Stretch goal: and in grams.