Session 6 Control structures: loops and conditions
First, read and work through Chapter 13.1 and 13.2 of R Programming for Data Science. Note: you can read the rest of this chapter but these first two parts give a good introduction.
6.1 if, else and for
To recap these important control functions we will play the game ‘fizz buzz.’ In this game, we say the numbers in order. If a number is divisible by 3, instead of saying the number we say ‘fizz.’ If the integer is divisible by 5, instead of saying the integer we say ‘buzz.’ If the number is divisible by both 3 and 5 we say ‘fizz buzz.’
I.e. ‘1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, 11, fizz, 13, 14, fizz-buzz, 16, ….’
Exercise: write a for
loop, containing if {} else {}
statements, to play fizz-buzz, over all numbers from 1 to 100.
Hints:
The
for
loop should iterate over the numbers from 1 to 100.The modulo operator in R is
%%
. For example,23 %% 5
returns 3, because 23 divided by 5 is 4, remainder 3.A number is divisible by both 5 and 3 if and only if it is divisible by 15.
For more help see Chapter 21 of Wickham & Grolemund.
6.2 Vectorised code
When possible, it is more efficient to use vectorised code. Here, we operate on every value in a vector at the same time instead of performing the task one by one as is done in a loop. We have already seen an example of this when multiplying a vector.
Exercise: rewrite the fizz-buzz exercise in a vectorized way.
Hint: break this into three steps, one for each replacement ‘fizz,’ ‘buzz’ and ‘fizz-buzz.’
6.3 Further Reading
- Chapter 10 of R Programming for Data Science on vectorisation.