R: For Loop

For loop is used to iterate over items of a sequence. It is also used as a control statement that enables us to easily construct a loop that has to run statements or a set of statements multiple times.

In for loop, the test condition is tested first before entering the body of the loop then the body of the loop is executed. If the test condition is false the loop body would not be executed.

Syntax

for (value in sequence)
{
  statement
}

Flowchart

R For Loop

Example

for (x in 1:7)
{
    print(x)
}

Output:

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7