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:
i
takes the first value from1
to3
, i.e. i=1;n
takes the first value from1
to3
, i.e. n=1;- The product of the current value of
i
andn
is computed and printed, i.e. i×n=1×1=1; n
takes the second value from1
to3
, i.e. n=2;- The product of the current value of
i
andn
is computed and printed, i.e. i×n=1×2=2; n
takes the third value from1
to3
, i.e. n=3;- The product of the current value of
i
andn
is computed and printed, i.e. i×n=1×3=3; i
takes the second value from1
to3
, i.e. i=2;- The product of the current value of
i
andn
is computed and printed, i.e. i×n=2×1=2; n
takes the second value from1
to3
, i.e. n=2;- The product of the current value of
i
andn
is computed and printed, i.e. i×n=2×2=4; n
takes the third value from1
to3
, i.e. n=3;- The product of the current value of
i
andn
is computed and printed, i.e. i×n=2×3=6; - Would you be able to follow up with the rest of the iteration?