Chapter 9 Iteration

One of the most powerful uses of any programming language is its ability to do a task over and over again really quickly - this is known as iteration.

Tip: Iteration isn’t actually the most efficient way of writing code, because it processes each item it iterates over one at a time. A more efficient way to process code is to ‘vectorise’ your code - this means writing code to process all the items at once. We’ve already done this when we’ve been manipulating columns of data in one go - we could have written an iterative function to go over each item in the column and manipulate it.

That said, iteration is a really important process to learn, because it helps you understand the sort of ‘decisions’ a computer will make in the background when executing code.

There are three types of iterative function that we’ll look at:

  • An if statement - a function that will do one thing if a condition is met or is true, and another thing is that condition is not met or is false
  • A for loop - a function that will repeat a task for every item in a list or a certain number of iterations
  • A while - function that will repeat a task for as long as a condition is met or is true

All of the functions here take a similar format:

9.1 if

As mentioned above, if statements are for carrying out an action if a condition is met or is true.

For example, say we were trying to create a recreate whether a fictitious teacher was male or female, if we knew the probability that a teacher was male, we could build an if statement that said:

  1. Generate a random number between 0 and 1
  2. If that number is less than or equal to the probability that a teacher is male, then say our fictitious teacher is male
  3. If that number is more than the probability that a teacher is male, then say our fictitious teacher is female

First, let’s work out the probability that a teacher is male. This is the average percentage of male teachers divided by 100, to make it a probability.

Now, let’s generate our random number using the runif function.

Now let’s write our if statement.

So now if our random number is less than or equal to the probability a teacher is male that it will print ‘M’. However, if it’s over the probability, nothing will happen.

To ensure something does happen we can use the else function, which will execute an action if the condition is not met.

Activity A9.1: How could we streamline the code we’ve just written by replacing object names?

9.2 for loops

A for loop - a function that will repeat a task for every item in a list or a certain number of iterations. Say we wanted to create a fictitious school which contained 10 teachers, we could write a for loop that for 10 iterations repeated the if statement above.

Let’s break this down the for loop argument:

  1. The i is the name of an object that will take a different value at each iteration (1st iteration, 2nd iteration, etc) of the for loop
  2. in 1:10 details the different values i will take: 1st iteration - i=1, 2nd iteration i=2, etc.
  3. The action to execute at each stage between the curly braces, which in this instance is the if statement from above

Activity A9.2: Adapt the for loop above to create an empty object and at each iteration add the result from the if statement to that object. The functions you’ll need are below:

9.3 while loops

A while loop while perform an action for as long as the condition specified in the function’s argument is true.

Activity A9.3: Write the function below out and run it. As 2 while always be greater than 1 what is going to happen?


Tip: Stop a bit of code from running by clicking on the red stop sign in the top right hand corner of the console.


Typically, a while loop will look like this:

Tip: paste0() is a really useful function that glues strings together. It’s different to c() in that it turns multiple strings into one string, whereas c() turns them into a vector of multiple strings.


Activity A9.4: Add 3 while loops after your for loop above so that while i equals 1 you add ‘Headteacher’ to an object, while i is less than 5 you add ‘Senior Leader’ to the same object, and while i is greater or equal to 5 you add ‘Classroom Teacher’ to the same object.

Once this has run put the gender object and the object denoting the seniority of the teacher into a dataframe called my_school with the column headings as gender and grade.

9.4 How could we use loops?

Loops are really useful for building models of systems, to use probabilities (as we did with the gender probabilities) to predict how entities (called agents in modelling) will behave in a system. These models can be run multiple times and the outputs recorded each time to give a distribution of how likely each outcome is to occur based on different behaviours along the modelled actions.