A for
loop in R is used to iterate over a sequence for a specific number of times. The number of iterations is determined by a conditional statement (the expression) within the for
loop.
To declare a for
loop in R, use the syntax below:
for(expression){
statement(s)
}
The expression
represents the given condition, while the statement
represents what the code should execute if the expression
is TRUE
.
for
loops are especially useful if you need to repeat the same code until a particular condition is met.
for (x in 1:5) {print(x)}
In the code above, we state a condition that for x
having values starting from 1
to 5
(these are the iterations), R should print all of the values of x
.
This for
loop is not like the for
keyword in other programming languages, but rather more of an iterator method that can be found in other object-oriented programming languages.
We can also print all the items of a list with a for
loop.
countries <- list("USA", "FRANCE", "UK", "CANADA")for (x in countries) {print(x)}
In the code above, we create a list
variable named countries
and use the for
loop to iterate over each item of the list. We then ask R to print all the items in the list.
Note: The
for
loop differs from thewhile
loop because thefor
loop does not require an index variable, unlike thewhile
loop.