Loops in R, break and next(continue)

Using break and next in R Loops

Using break and next in R Loops

In R, loops like for and while can be controlled using two special keywords: break and next. These help you stop or skip parts of the loop based on conditions.

1️⃣ Using break

The break statement is used to exit a loop immediately.

Example 1: Find the first number divisible by 7

for (i in 1:100) {
  if (i %% 7 == 0) {
    cat("First number divisible by 7 is:", i, "\n")
    break
  }
}
✅ This loop checks numbers from 1 to 100 and stops at the first number divisible by 7.

Example 2: Exit a while loop

i <- 1
while (TRUE) {
  if (i^2 > 50) {
    cat("Square of", i, "is greater than 50. Exiting loop.\n")
    break
  }
  i <- i + 1
}
✅ This infinite loop exits when the square of a number exceeds 50.

2️⃣ Using next (like continue)

The next statement skips the current iteration and moves to the next one.

Example 3: Skip even numbers

for (i in 1:10) {
  if (i %% 2 == 0) {
    next
  }
  cat(i, "is an odd number\n")
}
✅ Even numbers are skipped, and only odd numbers are printed.

Example 4: Skip NA values

numbers <- c(5, NA, 12, 3, NA, 9)

for (n in numbers) {
  if (is.na(n)) {
    next
  }
  cat("Square of", n, "is", n^2, "\n")
}
✅ The loop skips over NA values to avoid errors.

3️⃣ Using break and next together

Example 5: Mixed usage

for (i in 1:20) {
  if (i %% 2 == 0) {
    next  # Skip even numbers
  }
  if (i > 10) {
    cat("Reached the limit. Breaking loop.\n")
    break
  }
  cat("Processing odd number:", i, "\n")
}
✅ The loop skips even numbers and breaks once the value goes beyond 10.

📋 Summary Table

Statement Function Use Case
break Exits the loop immediately When a match or limit is found
next Skips current iteration Ignore certain values or invalid data

These simple but powerful tools can make your R loops smarter and more efficient!

Post a Comment

Me
Me
WhatsApp Contact Me on WhatsApp
×

📩 Today’s Programming Tip

✅ Python Tip: Use unpacking for swapping values.
Example:
a, b = 5, 10
a, b = b, a
print(a, b)

🔗 Learn More

💡 Tip of the Day