Continue Statement in R
In this tutorial, we will learn about the next statement in R. We will cover the basics of using the next statement to skip the current iteration of a loop and proceed with the next iteration.
What is a Next Statement
A next statement is used to skip the current iteration of a loop and proceed with the next iteration. When a next statement is encountered, the remaining code inside the loop for the current iteration is skipped, and the loop continues with the next iteration.
Syntax
The syntax for the next statement in R is:
nextThe next statement can be used in for loops and while loops to skip the current iteration and proceed with the next iteration.
Example 1: Skipping Even Numbers in a For Loop
- Use a for loop to iterate from 1 to 10.
- Inside the loop, use an if statement to check if the current iteration is even.
- If the condition is true, use a next statement to skip the current iteration.
R Program
for (i in 1:10) {
if (i %% 2 == 0) {
next
}
print(i)
}Output
[1] 1 [1] 3 [1] 5 [1] 7 [1] 9
Example 2: Skipping Odd Numbers in a While Loop
- Declare an integer variable
iand initialize it to 1. - Use a while loop to iterate while
iis less than or equal to 10. - Inside the loop, use an if statement to check if
iis odd. - If the condition is true, use a next statement to skip the current iteration.
R Program
i <- 1
while (i <= 10) {
if (i %% 2 != 0) {
i <- i + 1
next
}
print(i)
i <- i + 1
}Output
[1] 2 [1] 4 [1] 6 [1] 8 [1] 10