Practice: Loops

Stat 133

Author

Gaston Sanchez

Learning Objectives
  • Get familiar with the syntax of a for loop
  • Write simple for loops

1 About Loops

  • Many times we need to perform a procedure several times

  • In other words, we have to perform the same operation several times as long as some condition is fulfilled

  • For this purpose we use loops

  • The main idea is that of iteration or repetition

  • R provides three basic paradigms to handle this situations: for() loops, while loops, and repeat loops.


2 Examples: Counting Letters

Consider the following vector letrs which contains various letters:

letrs <- c(
  'y', 'd', 'g', 'a', 'b', 'w', 'k', 'n', 'r', 's', 
  'a', 'u', 'u', 'j', 'v', 'n', 'j', 'g', 'i', 'o', 
  'u', 'e', 'i', 'y', 'n', 'e', 'e', 'b', 'j', 'y', 
  'l', 'o', 'a', 't', 'c', 'f', 'j', 'j', 'f', 'o', 
  't', 't', 'z', 'l', 'y', 'w', 'f', 'y', 'h', 'l', 
  'y', 'w', 'x', 'f', 'z', 'g', 's', 'j', 'f', 'x', 
  'n', 'b', 'm', 'r', 'v', 'n', 'f', 'a', 's', 's', 
  'h', 'f', 'w', 'l', 'f', 'h', 'g', 'k', 'q', 'd', 
  'm', 'h', 'y', 'p', 'y', 'w', 'n', 't', 'g', 'm', 
  'v', 'l', 'p', 'a', 'm', 'u', 'f', 'q', 'i', 'g'
)

2.1 Counting a’s with vectorized code

Say we are interested in counting the number of letters "a". This can be easily done in R with some vectorized code:

sum(letrs == 'a')
[1] 5

For learning purposes, we are going to ask you to forget about vectorization for a moment. And instead let’s see how to use loops.

2.2 Counting a’s with a for loop

Alternatively, we can also write a for loop that iterates through each element of letrs, testing whether we have an "a", and if yes, the count increases by one.

# start at count zero
count_a = 0

for (pos in 1:length(letrs)) {
  # increase count if letter is an 'a'
  if (letrs[pos] == 'a') {
    count_a = count_a + 1
  }
}

count_a
[1] 5

2.3 Counting x, y and z with a for loop

Say we are interested in counting the number of x, y and z letters, using a for loop. Here’s one possibility:

# start at count zero
count_xyz = 0

for (pos in 1:length(letrs)) {
  # increase count if letter is x, y, or z
  if (letrs[pos] %in% c('x', 'y', 'z')) {
    count_xyz = count_xyz + 1
  }
}

count_xyz
[1] 12

2.4 Stopping a loop with break

Say we are interested in counting the number of x, y and z letters, using a for loop, but this time, we only want to count until we get the fifth occurrence.

# start at count zero
count_xyz = 0

for (pos in 1:length(letrs)) {
  # increase count if letter is x, y, or z
  if (letrs[pos] %in% c('x', 'y', 'z')) {
    count_xyz = count_xyz + 1
  }
  # break loop if count gets to fifth occurrence
  if (count_xyz == 5) {
    break
  }
}

count_xyz
[1] 5

Notice the use of the break statement to decide whether the loop should stop from iterating.


3 Your Turn: Counting Letters

3.1 Number of letters different from "b"

Consider the vector letrs defined in the previous section. Write a for loop in order to count the number of letters different from "b"

Show answer
# start count at zero
count_not_b = 0

for (pos in 1:length(letrs)) {
  # increase count if letter is not a 'b'
  if (letrs[pos] != 'b') {
    count_not_b = count_not_b + 1
  }
}

count_not_b

3.2 Number of "f" or "w" in even positions

Consider the vector letrs. Write a for loop in order to count the number of letters equal to f or w that are in even positions (e.g.  2, 4, …, 100). Hint: the function seq() is your friend.

Show answer
# start count at zero
count_fw = 0

for (pos in seq(2, 100, by = 2)) {
  # increase count if letter is 'f' or 'w'
  if (letrs[pos] == 'f' | letrs[pos] == 'w') {
    count_fw = count_fw + 1
  }
}

count_fw

3.3 Counting vowels

Consider the vector letrs. Write a for loop in order to count the number of vowels, until reaching exactly 15 vowels. How many iterations were necessary to obtain 15 vowels?

Show answer
# start count at zero
count_vowels = 0

for (pos in 1:length(letrs)) {
  # increase count if letter is a vowel
  if (letrs[pos] %in% c('a', 'e', 'i', 'o', 'u')) {
    count_vowels = count_vowels + 1
  }
  if (count_vowels == 15) {
    break
  }
}

# number of iterations
pos

4 Summation Series

  1. Write a for loop to compute the following series. Test your code with different values for \(n\). Does the sum of the series converge as \(n\) increase?

\[ \sum_{k=0}^{n} \frac{1}{2^k} = 1 + \frac{1}{2} + \frac{1}{4} + \frac{1}{8} + \dots + \frac{1}{2^n} \]

Show answer
# Summation Series of 1/2
n = 10
series = 0
sum_series = 0

for (k in 0:n) {
  term = 1 / (2^k)
  series[k+1] = term
  sum_series = sum_series + term
}

# with n=10, the series is
series

# the sum of the series is
sum_series
  1. Write a for loop to compute the following series. Test your code with different values for \(n\). Does the sum of the series converge as \(n\) increase?

\[ \sum_{k=0}^{n} \frac{1}{9^k} =1 + \frac{1}{9} + \frac{1}{81} + \dots + \frac{1}{9^n} \]

Show answer
# Summation Series of 1/9
n = 20

# outputs
series = 0
sum_series = 0

# iterations
for (k in 0:n) {
  term = 1 / (9^k)
  series[k+1] = term
  sum_series = sum_series + term
}

# with n=10, the series is
series

# the sum of the series is
sum_series

4.1 Arithmetic Series

Consider the following arithmetic series

\[ a_n = a_1 + (n-1)d \]

Write a for loop to compute this series when \(a_1 = 3\), and \(d = 3\). For instance: \(3 + 6 + 12 + 24 + \dots\). Test your code with different values for \(n\). Does the series converge as \(n\) increase?

Show answer
# inputs
a1 = 3
d = 3
num = 10

# outputs
series = rep(0, num)
sum_series = 0

# iterations
for (n in 1:num) {
  an = a1 + (n-1)*d
  series[n] = an
  sum_series = sum_series + an
}

# series does not converge as 'n' increases

4.2 Geometric Sequence

A sequence such as \(3, 6, 12, 24, 48\) is an example of a geometric sequence. In this type of sequence, the \(n\)-th term is obtained as:

\[ a_n = a_1 \times r^{n-1} \]

where: \(a_1\) is the first term, \(r\) is the common ratio, and \(n\) is the number of terms.

Write a for loop to compute the sum of the first \(n\) terms of: \(3 + 6 + 12 + 24 + \dots\). Test your code with different values for \(n\). Does the series converge as \(n\) increase?

Show answer
# inputs
a1 = 3
r = 2

# outputs
summ = 0

for (n in 1:10) {
  an = a1 * r^(n-1)
  summ = summ + an
}

# series does not converge as 'n' increases