Chapter 14 for loops within for loops

In some cases, you may want to use nested loops to accomplish a task. When using nested loops, it is important to use different variables for each one of your loops.

In the example below, we used a nested for framework which printed the product of i and n, where n was part of the nested for and was a sequence from 1 to 3, and then i, which was also a sequence from 1 to 3, was part of the outer loop.

for (i in 1:3) {
    for (n in 1:3) {
        print(i * n)
    }
}
## [1] 1
## [1] 2
## [1] 3
## [1] 2
## [1] 4
## [1] 6
## [1] 3
## [1] 6
## [1] 9

Specifically, the operation above beings as follows:

  1. i takes the first value from 1 to 3, i.e. \(i = 1\);
  2. n takes the first value from 1 to 3, i.e. \(n = 1\);
  3. The product of the current value of i and n is computed and printed, i.e. \(i \times n = 1 \times 1 = 1\);
  4. n takes the second value from 1 to 3, i.e. \(n = 2\);
  5. The product of the current value of i and n is computed and printed, i.e. \(i \times n = 1 \times 2 = 2\);
  6. n takes the third value from 1 to 3, i.e. \(n = 3\);
  7. The product of the current value of i and n is computed and printed, i.e. \(i \times n = 1 \times 3 = 3\);
  8. i takes the second value from 1 to 3, i.e. \(i = 2\);
  9. The product of the current value of i and n is computed and printed, i.e. \(i \times n = 2 \times 1 = 2\);
  10. n takes the second value from 1 to 3, i.e. \(n = 2\);
  11. The product of the current value of i and n is computed and printed, i.e. \(i \times n = 2 \times 2 = 4\);
  12. n takes the third value from 1 to 3, i.e. \(n = 3\);
  13. The product of the current value of i and n is computed and printed, i.e. \(i \times n = 2 \times 3 = 6\);
  14. Would you be able to follow up with the rest of the iteration?