R – while loop next
R
# Set an initial value for a variable x <- 1 # Loop while x is less than 10 while (x < 10) { if (x == 3) { # Skip iteration when x is 3 x <- x + 1 next } print ( paste ( "The current value of x is:" , x)) x <- x + 1 } # Print a message after the loop has finished print ( "The loop has ended." ) |
Output
[1] "The current value of x is: 1" [1] "The current value of x is: 2" [1] "The current value of x is: 4" [1] "The current value of x is: 5" [1] "The current value of x is: 6" [1] "The current value of x is: 7" [1] "The current value of x is: 8" [1] "The current value of x is: 9"
In this instance, x’s initial value is set to 1 at the beginning. Then, as long as x is less than 10, we continue iterating using a while-loop. We use an if statement inside the loop to see if x equals 3. If so, the loop’s current iteration is skipped in favor of the following one using the next statement. If not, we use the x – x + 1 expression to increment x by 1 and output a message stating the current value of x.
The next line instructs R to move on to the next iteration of the loop and skip the current one. based on a condition, over a subset of the loop’s iterations without ever leaving the loop.
R – while loop
While loop in R programming language is used when the exact number of iterations of a loop is not known beforehand. It executes the same code again and again until a stop condition is met. While loop checks for the condition to be true or false n+1 times rather than n times. This is because the while loop checks for the condition before entering the body of the loop.
R- While loop Syntax:
while (test_expression) { statement update_expression }