R For Loop
R For Loop executes a set of statements for each of the elements in a vector provided to it. We shall learn syntax and execution of for loop with example R scripts.
We shall go through following topics in this tutorial.
Syntax
The syntax of For Loop in R is
for (x in vector) {
statement(s)
}
Execution Flow
The following flow chart depicts the flow of execution for a For Loop in R.
The statements in the for loop are executed for each element in vector. And when there are no further elements in the vector, the execution control is out of the for loop and continues executing statements after for loop.
Example 1 – For Loop
An example program of for loop iterating over elements of an integer vector.
r_for_loop_ex.R
# R for loop Example
a = c(2, 45, 9, 12)
for(i in a) {
print(i)
}
Output
$ Rscript r_for_loop_ex.R
[1] 2
[1] 45
[1] 9
[1] 12
Example 2 – Break statement inside For Loop
A for loop could be broken abruptly using r break statement intentionally inside the for loop. An example is provided below.
r_for_loop_break_ex.R
# R for loop example with break statement
a = c(12, 45, 9, 12)
for(i in a) {
if(i==9){
break
}
print(i)
}
Output
$ Rscript r_for_loop_break_ex.R
[1] 12
[1] 45
The inclusion of break statement might look similar to R Repeat Loop Statement.
Conclusion
In this R Tutorial – R for loop, we have learnt about the syntax and execution flow of for loop with Example R scripts.