🔄 R Loops: Making Things Happen Again and Again!
The Magic of Loops
Imagine you have a toy robot that can do one task. Cool, right? But what if you need it to do the same task 100 times? Would you press the button 100 times? That sounds exhausting!
Loops are like teaching your robot to repeat tasks automatically. You say “do this 10 times” and it just does it. No more pressing buttons!
🎢 The Merry-Go-Round Analogy
Think of loops like a merry-go-round at a playground:
- for loop = A merry-go-round that spins exactly 5 times, then stops
- while loop = A merry-go-round that keeps spinning while kids are still on it
- repeat loop = A merry-go-round that spins forever until someone presses the STOP button
- break = The STOP button - makes everything stop immediately
- next = The “skip this seat” button - skips one turn but keeps going
🎯 The for Loop
What is it?
A for loop says: “Do this thing for each item in my list.”
It’s like a teacher calling each student’s name one by one.
Simple Example
# Say hello to 3 friends
for (friend in c("Anna", "Ben", "Cara")) {
print(paste("Hello,", friend))
}
Output:
[1] "Hello, Anna"
[1] "Hello, Ben"
[1] "Hello, Cara"
Counting with for
# Count from 1 to 5
for (number in 1:5) {
print(number)
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
How It Works
graph TD A["Start for loop"] --> B["Pick first item"] B --> C["Do the task"] C --> D{More items?} D -->|Yes| E["Pick next item"] E --> C D -->|No| F["Done!"]
Real Life Example
Imagine you have a basket of apples. You want to check each one:
apples <- c("red", "green", "red", "yellow")
for (apple in apples) {
print(paste("This apple is", apple))
}
🔄 The while Loop
What is it?
A while loop says: “Keep doing this WHILE something is true.”
It’s like eating cookies while there are still cookies in the jar!
Simple Example
# Count down from 5
countdown <- 5
while (countdown > 0) {
print(countdown)
countdown <- countdown - 1
}
print("Blast off!")
Output:
[1] 5
[1] 4
[1] 3
[1] 2
[1] 1
[1] "Blast off!"
How It Works
graph TD A["Start while loop"] --> B{Is condition TRUE?} B -->|Yes| C["Do the task"] C --> D["Update something"] D --> B B -->|No| E["Done!"]
Important Warning!
Always make sure your while loop can stop! If not, it runs forever!
# GOOD: This stops when count reaches 0
count <- 3
while (count > 0) {
print(count)
count <- count - 1 # Makes count smaller
}
# BAD: This never stops! (Don't run this!)
# while (TRUE) {
# print("Forever...")
# }
🔁 The repeat Loop
What is it?
A repeat loop says: “Keep doing this forever… until I say STOP!”
It’s like a song on repeat - it plays forever until you press stop.
Simple Example
# Keep asking until we get the magic word
counter <- 1
repeat {
print(paste("Attempt", counter))
if (counter == 3) {
print("Success! Stopping now.")
break # This is the STOP button!
}
counter <- counter + 1
}
Output:
[1] "Attempt 1"
[1] "Attempt 2"
[1] "Attempt 3"
[1] "Success! Stopping now."
How It Works
graph TD A["Start repeat loop"] --> B["Do the task"] B --> C{Should I stop?} C -->|No| B C -->|Yes - break!| D["Done!"]
Key Rule
A repeat loop MUST have a break inside it. Otherwise, it runs forever!
🛑 Loop Control: break
What is it?
break is like an emergency exit. It says: “STOP everything right now and leave the loop!”
Example: Stop at First Problem
numbers <- c(2, 4, 6, -1, 8, 10)
for (num in numbers) {
if (num < 0) {
print("Found a negative! Stopping!")
break
}
print(paste("Checked:", num))
}
Output:
[1] "Checked: 2"
[1] "Checked: 4"
[1] "Checked: 6"
[1] "Found a negative! Stopping!"
Notice how 8 and 10 were never checked? The loop stopped!
⏭️ Loop Control: next
What is it?
next is like saying: “Skip this one and move to the next!”
It’s like skipping a song you don’t like but keeping the playlist going.
Example: Skip Odd Numbers
for (num in 1:6) {
if (num %% 2 != 0) { # Check if odd
next # Skip this number!
}
print(paste(num, "is even!"))
}
Output:
[1] "2 is even!"
[1] "4 is even!"
[1] "6 is even!"
The odd numbers (1, 3, 5) were skipped!
break vs next
graph TD A["Loop Running"] --> B{Problem found?} B -->|Use break| C["EXIT loop completely"] B -->|Use next| D["SKIP this round only"] D --> E["Continue to next item"]
| Situation | Use This |
|---|---|
| Want to stop everything | break |
| Want to skip one item | next |
🎨 Choosing the Right Loop
| If you want to… | Use this loop |
|---|---|
| Do something for each item | for |
| Keep going while something is true | while |
| Keep going until you decide to stop | repeat |
Quick Decision Tree
graph TD A["What do I need?"] --> B{Know how many times?} B -->|Yes| C["Use for loop"] B -->|No| D{Have a condition?} D -->|Yes| E["Use while loop"] D -->|No| F["Use repeat loop"]
🌟 Putting It All Together
Here’s a fun example using everything we learned:
# Game: Find the treasure!
boxes <- c("empty", "empty", "treasure",
"empty", "monster")
for (i in 1:length(boxes)) {
box <- boxes[i]
if (box == "empty") {
print(paste("Box", i, "is empty. Next!"))
next # Skip to next box
}
if (box == "monster") {
print("MONSTER! Run away!")
break # Stop the game!
}
if (box == "treasure") {
print("TREASURE FOUND! You win!")
break # Stop - we won!
}
}
Output:
[1] "Box 1 is empty. Next!"
[1] "Box 2 is empty. Next!"
[1] "TREASURE FOUND! You win!"
🎉 You Did It!
Now you know:
forloop - Do something for each itemwhileloop - Keep going while condition is truerepeatloop - Keep going until you say stopbreak- Emergency stop buttonnext- Skip and continue
Loops are your superpower for making R do repetitive tasks. No more doing things 100 times by hand! 🚀
