Lecture 6: Control Statements
WHILE; BREAK; NEXT
Ivan Belik
Assembled and built based on:
[Link]
[Link]
[Link]
[Link]
WHILE
R: while - statement
• while repeatedly executes a block of statements as long as a condition is TRUE
• Repetition of statements (B in figure) using while is called iteration
• The while statement is also called the while-loop
• The while-loop is used to repeat a section of code an unknown number of
times until a specific condition is met
• Formal WHILE – notation in R:
while (testing expression) {
statement
}
R: while - statement
while (testing expression) {
• Example: statement
}
Print all elements from 1 to 4:
R: while - statement
• Consider another example based on iris data frame:
R: while - statement
• Let’s make our example a bit more interesting
• We will create a new empty data frame called My_frame
• My_frame will have one variable [Link] (the same name as in the iris data frame)
• Next, we fill My_frame by [Link] values (from iris) that are greater than 7.5
• We will employ WHILE-statement to solve this problem
R: while - statement
BREAK
R: break - statement
• Break statement: used to break out of a loop statement
• To stop the execution of a looping statement even if:
• the loop condition has not become FALSE
or
• Statements has not been completely iterated over
R: break in for - statement
• EXAMPLE 1:
• We iterate over the vector a (a <- 1:10) and show values until we meet value 4:
R: break in for - statement
• EXAMPLE 2:
• We Iterate over three vectors within 3-level for-loop
• We break for-loop on the 3-rd level every time when we approach value 2 in the vector 1:10
R: break in while - statement
• BREAK - statement can be used in WHILE-loop as well
• In the following example we start to sum numbers from 1 to 5,
• but we “break” the procedure if sum becomes equal to 3
NEXT
R: next – statement in FOR
next-statement is applied when you need to:
• skip the current iteration,
• but do not terminate the loop
Here, next statement in a for-loop:
We do not print 4, but keep going to print all other numbers till 10
R: next – statement in WHILE
next-statement is applied when you need to:
• skip the current iteration,
• but do not terminate the loop
Here, next statement in a while-loop:
We do not print 3, but keep going to print all other numbers till 5
Optional materials:
more examples
R: repeat - loop
• Repeat loop is less popular than FOR and WHILE, but can be useful
• R Programming repeat loop:
• [Link]
R: Conditionals and loops
• Let’s consider some trivial examples related to the combined statements in R.
• EXAMPLES ([Link]
IF + WHILE:
[Link]
[Link]
IF + FOR:
[Link]