# How to Write Nested for-Loops in R (Example Code)

In this tutorial you’ll learn how to nest loops in R programming.

## Example: Two Nested for-Loops in R

for(i in 1:2) { # Starting outer loop for(j in 1:3) { # Starting inner loop print(paste0("i", i, " & j", j)) # Some output } } # [1] "i1 & j1" # [1] "i1 & j2" # [1] "i1 & j3" # [1] "i2 & j1" # [1] "i2 & j2" # [1] "i2 & j3" |

for(i in 1:2) { # Starting outer loop for(j in 1:3) { # Starting inner loop print(paste0("i", i, " & j", j)) # Some output } } # [1] "i1 & j1" # [1] "i1 & j2" # [1] "i1 & j3" # [1] "i2 & j1" # [1] "i2 & j2" # [1] "i2 & j3"