Week 6: Automating Repetitive Tasks with Loops
Learn how to use `for` and `while` loops in R to execute code repeatedly.
Explore Chapter 6`break` and `next` Statements: Controlling Loop Execution.
You can alter the standard flow of loops using the `break` and `next` statements.
`break` Statement
The `break` statement immediately terminates the innermost loop (`for` or `while`) it is contained within. Execution continues with the first statement after the terminated loop.
for (i in 1:10) {
print(i)
if (i == 5) {
print("Found 5, stopping loop.")
break # Exit the loop
}
}
# Output: 1 2 3 4 5 "Found 5, stopping loop."
`next` Statement
The `next` statement skips the rest of the current iteration of a loop and immediately proceeds to the next iteration. It's similar to `continue` in other languages like Python.
for (i in 1:7) {
if (i %% 2 == 0) { # Check if i is even
print(paste("Skipping even number:", i))
next # Go to the next iteration
}
print(paste("Processing odd number:", i))
}
# Output:
# [1] "Processing odd number: 1"
# [1] "Skipping even number: 2"
# [1] "Processing odd number: 3"
# [1] "Skipping even number: 4"
# [1] "Processing odd number: 5"
# [1] "Skipping even number: 6"
# [1] "Processing odd number: 7"