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:
itakes the first value from1to3, i.e. \(i = 1\);ntakes the first value from1to3, i.e. \(n = 1\);- The product of the current value of
iandnis computed and printed, i.e. \(i \times n = 1 \times 1 = 1\); ntakes the second value from1to3, i.e. \(n = 2\);- The product of the current value of
iandnis computed and printed, i.e. \(i \times n = 1 \times 2 = 2\); ntakes the third value from1to3, i.e. \(n = 3\);- The product of the current value of
iandnis computed and printed, i.e. \(i \times n = 1 \times 3 = 3\); itakes the second value from1to3, i.e. \(i = 2\);- The product of the current value of
iandnis computed and printed, i.e. \(i \times n = 2 \times 1 = 2\); ntakes the second value from1to3, i.e. \(n = 2\);- The product of the current value of
iandnis computed and printed, i.e. \(i \times n = 2 \times 2 = 4\); ntakes the third value from1to3, i.e. \(n = 3\);- The product of the current value of
iandnis computed and printed, i.e. \(i \times n = 2 \times 3 = 6\); - Would you be able to follow up with the rest of the iteration?