R for Loop

Loops are used in programming to repeat a specific block of code. In this article, you will learn to create a for loop in R programming.

A for loop is used to iterate over a vector in R programming.


Syntax of for loop

for (val in sequence)
{
statement
}

Here, sequence is a vector and val takes on each of its value during the loop. In each iteration, statement is evaluated.


Flowchart of for loop

r for loop flowchart

Example: for loop

Below is an example to count the number of even numbers in a vector.

x <- c(2,5,3,9,8,11,6)
count <- 0
for (val in x) {
if(val %% 2 == 0)  count = count+1
}
print(count)

Output

[1] 3

In the above example, the loop iterates 7 times as the vector x has 7 elements.

In each iteration, val takes on the value of corresponding element of x.

We have used a counter to count the number of even numbers in x. We can see that x contains 3 even numbers.


Check out these examples to learn more about for loop:

Did you find this article helpful?