For Loop in R

A loop is a sequence of instructions repeated until a specific condition is reached. R provides loops to deal with repetitive tasks, the most common of which is For Loop. For Loop performs the same operations on all elements from the input.

For Loop Syntax

for(variable in sequence){
expression
}

Arguments

  • for = it is a keyword
  • in = it is a keyword
  • variable = it can take any name.
  • sequence  = it can be a vector, range, array, or list.

For Loop Flowchart

For Loop Flowchart
Flow chart of the For Loop.

Example 1: Printing a range of numbers

for (i in 1:10){
print(i)
}

Output

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

In this example, we iterated over the range 1 to 10 and printed the ten values, i.e., one value for each repetition.

Example 2: Iterating over the items in a vector

superheroes <- c(”Batman”, “Superman”, “Aquaman”)
for (i in superheroes){
print(i)
}

Output

[1] "Batman"
[1] "Superman"
[1] "Aquaman"

In this example, we iterated over the items inside the vector and printed them simultaneously.

Leave a Comment