3.4 Scratch for Iterative Processes

In this case, the map function is sufficient since the scraped results for the Denver Broncos does not depend on the scraped results for the Dallas Cowboys. If the results of one iteration (e.g. the scraped results for the Denver Broncos) depended on the results of prior iterations (e.g. scraped results for the Dallas Cowboys), then the algorithm to scrape team statistics is recursive. When we have a recursive algorithm, the map function is often insufficient or overly complex. In this case, we may reach for a for-loop using the for function.

A for-loop allows us to repeat code multiple times making small changes with each iteration. To illustrate the concept of a for-loop, let’s consider a famous example of a recursive algorithm: the Fibonacci sequence. The Fibonacci sequence is a sequence of integers starting with 0 and 1 where each following integer is the sum of the previous two integers. Written out, the first eight values of the Fibonacci sequence are \(0, 1, 1, 2, 3, 5, 8, 13\). Let’s consider how to use a for-loop to return the first \(n\) integers in the Fibonacci sequence. Let’s consider \(n=8\) to start.

n <- 8
fib_seq <- vector(mode = 'integer', length = n)
for(i in 1:n){
  # if it is the first element of the Fibonacci sequence, return a 0
  if(i == 1){
    fib_seq[i] <- 0
  }
  # if it is the second element of the Fibonacci sequence, return a 1
  else if(i == 2){
    fib_seq[i] <- 1
  }
  # if it is any other element of the Fibonacci sequence, return the sum of the 
  # previous two elements
  else{
    fib_seq[i] <- fib_seq[i-1] + fib_seq[i-2]
  }
}
fib_seq
[1]  0  1  1  2  3  5  8 13

Since each value of the Fibonacci sequence depends on the results of the prior two values of the Fibonacci sequence, a for-loop allows us to index the results of the sequence with each iteration. While intuitive, the for-loops can be very slow in R, especially when the recursive algorithm becomes more complex. In these situations, we need a faster alternative.