A break
statement in R is used to stop a loop from executing, even while the condition provided is True
.
A for
loop in R is used for iterating over a sequence for a specific number of times. The number of iterations or repetitions is determined or defined by a conditional statement, the expression, within the for
loop.
To declare a for
loop in R, take a good look at its syntax below:
for(expression){
statement(s)
}
From the syntax shown above, we can see that the expression
represents the given condition, while the statement
represents what the code should execute if the expression
is True
.
The importance of the for
loop is such that it is required when there is a need for a repetition of the same code, until a particular condition is met.
To better understand how the for
loop works, let’s look at the examples given below:
for (x in 1:5) {print(x)}
In the code given above, we stated a condition that for x
having values ranging from 1
to 5
(these are the iterations), R
should print all the values of x
.
We can stop a for
loop before it iterates through all the items provided in the condition, using the break
statement.
In the example below, we are creating a list
variable and, using the break
statement, we will stop the iteration at a specified item in the list.
countries <- list("USA", "FRANCE", "UK", "CANADA")for (x in countries) {if (x == "CANADA"){break}print(x)}
From the code given above, the loop will stop at "CANADA"
, because we chose to finish the loop by using the break
statement when x is equal to "CANADA"
(x == "CANADA"
).