Introduction
In this chapter, you will learn about the next
statement in R. The next
statement is used within loops to skip the current iteration and move to the next iteration. This is useful when you want to bypass certain conditions in a loop without exiting the loop entirely.
The next Statement
Basic Usage
The next
statement is used within loops (such as for
, while
, or repeat
loops) to skip the rest of the code in the current iteration and proceed to the next iteration.
Syntax
for Loop:
for (variable in sequence) {
if (condition) {
next
}
# Code to execute if condition is FALSE
}
while Loop:
while (condition) {
if (inner_condition) {
next
}
# Code to execute if inner_condition is FALSE
}
repeat Loop:
repeat {
if (condition) {
next
}
# Code to execute if condition is FALSE
}
Examples
Example 1: Using next in a for Loop
In this example, the next
statement is used to skip even numbers in a sequence.
Example:
# Using next in a for loop
for (i in 1:10) {
if (i %% 2 == 0) {
next # Skip even numbers
}
print(i)
}
# Output: 1 3 5 7 9
Example 2: Using next in a while Loop
In this example, the next
statement is used to skip iterations when a condition is met in a while
loop.
Example:
# Using next in a while loop
i <- 1
while (i <= 10) {
i <- i + 1
if (i %% 2 == 0) {
next # Skip even numbers
}
print(i)
}
# Output: 3 5 7 9 11
Example 3: Using next in a repeat Loop
In this example, the next
statement is used within a repeat
loop to skip certain iterations.
Example:
# Using next in a repeat loop
i <- 1
repeat {
if (i > 10) {
break # Exit the loop
}
if (i %% 2 == 0) {
i <- i + 1
next # Skip even numbers
}
print(i)
i <- i + 1
}
# Output: 1 3 5 7 9
Example Program with next Statement
Here is an example program that demonstrates the use of the next
statement in R:
# R Program to Demonstrate next Statement
# Using next to skip numbers divisible by 3
for (i in 1:15) {
if (i %% 3 == 0) {
next # Skip numbers divisible by 3
}
print(i)
}
# Output: 1 2 4 5 7 8 10 11 13 14
# Using next in a while loop to skip numbers greater than 10
i <- 1
while (i <= 15) {
if (i > 10) {
next # Skip numbers greater than 10
}
print(i)
i <- i + 1
}
# Output: 1 2 3 4 5 6 7 8 9 10
# Using next in a repeat loop to skip numbers less than 5
i <- 1
repeat {
if (i >= 10) {
break # Exit the loop
}
if (i < 5) {
i <- i + 1
next # Skip numbers less than 5
}
print(i)
i <- i + 1
}
# Output: 5 6 7 8 9
Conclusion
In this chapter, you learned about the next
statement in R, including how to use it within for
, while
, and repeat
loops. The next
statement allows you to skip the current iteration and move to the next iteration, which can be useful for bypassing certain conditions without exiting the loop. By mastering the next
statement, you can write more flexible and efficient loop structures in your R programs.