Session 7 Writing your own functions

First, work through Chapter 26 of R for Data Science, then work through the exercises below to check your understanding.

7.1 Writing your own functions

Now let’s try and generalise the fizz-buzz approach above by writing it into a function.

Exercise: write a function fizz_buzz that takes a single argument, n, that plays fizz-buzz for all the numbers up to and including n.

Hint: this will look like:

fizz_buzz <- function(n){
  #some code, very much like what you wrote above.
}

7.1.1 Writing robust functions

This is a more advanced section: skip if you are low on time.

What happens if you try to run your fizz_buzz function as fizz_buzz(100.2), or fizz_buzz('hello'), or fizz_buzz(-3)? Or (even more subtle) fizz_buzz(0)? It would be good if your function did something appropriate with these inputs.

Exercise: extend your function so that it handles these inputs better.

Hints:

  1. If the input is inappropriate you could throw an error. For example:
if(!is.integer(x)){
  stop("x needs to be an integer")
}

See ?is.integer and others, ?is.character etc.

  1. Another alternative might be to round a non-integer using round.