R Nested Loops

🔁🔁 R Nested Loops

Nested loops in R mean a loop inside another loop.

They are commonly used when working with tables, matrices, patterns, or multi-dimensional data.


🔹 What is a Nested Loop?

  • Outer loop runs first

  • Inner loop runs completely for each iteration of the outer loop

👉 Inner loop executes multiple times.


🔹 1. Nested for Loop (Basic Example)

for (i in 1:3) {
for (j in 1:2) {
print(paste("i =", i, "j =", j))
}
}

Output:

[1] "i = 1 j = 1"
[1] "i = 1 j = 2"
[1] "i = 2 j = 1"
[1] "i = 2 j = 2"
[1] "i = 3 j = 1"
[1] "i = 3 j = 2"

🔹 2. Nested Loop for Multiplication Table

for (i in 1:5) {
for (j in 1:10) {
cat(i, "x", j, "=", i*j, "\n")
}
cat("\n")
}

✔ Useful for tables and patterns


🔹 3. Nested Loop with while

i <- 1

while (i <= 3) {
j <- 1
while (j <= 2) {
print(paste(“i =”, i, “j =”, j))
j <- j + 1
}
i <- i + 1
}


🔹 4. Nested Loop with break

for (i in 1:3) {
for (j in 1:3) {
if (j == 2) {
break
}
print(paste("i =", i, "j =", j))
}
}

break exits inner loop only


🔹 5. Nested Loop with next

for (i in 1:3) {
for (j in 1:3) {
if (j == 2) {
next
}
print(paste("i =", i, "j =", j))
}
}

✔ Skips only the current inner iteration


🔹 6. Common Use Cases of Nested Loops

✔ Working with matrices
✔ Creating patterns
✔ Comparing each element with others
✔ Multi-level data processing


🔹 Performance Tip ⚠️

Nested loops can be slow for large data.
👉 Prefer vectorized operations or apply() functions when possible.


📌 Summary

  • Nested loop = loop inside another loop

  • Inner loop runs fully for each outer loop iteration

  • Can use for or while

  • break and next affect inner loop

  • Useful but avoid for very large data

You may also like...