# For Loop in R: The Complete Guide

Loops are the most frequently used snippet in any programming language, and R is no different. All modern programming languages implement special structures that allow the repetition of code instructions.

## What is a loop in R

Loops in R are used to repeat a specific block of code instructions. Over the years, there are lots of words like “Looping”, “cycling”, “iterating” are used to repeat certain code to achieve our final goal. This block of code is called a loop.

There are two types of loops in R

1. While loop in r: This kind of loop is based on the verification of a logical condition.  We have seen while loop in this blog.
2. For loop in r: This type of loop is executed for a defined number of times, as controlled by a counter, incremented at each repetition cycle. Let’s deep dive into the R for loop.

## For loop in R

The for loop in R is used to iterate over a vector. A for loop executes for each item within a series. The code present in the body is executed until the end of the series is reached. The execution stops after the last item of the series is processed.

### Syntax of for loop

``````for (item in sequence)
{
statement
}``````

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

### Flow chart of for loop In the flow chart, rectangular boxes mean something like “do something which does not imply decisions”.

The diamonds, on the other hand, are called “decision symbols” and therefore interpret them into questions that only have two possible logical answers, specifically, TRUE(T) or FALSE(F).

In general, the for loop is made up of the rectangular box ‘init’, the diamond or rhombus decision, and the rectangular box is executed a known number of times.

### Example

For loop in R is especially flexible in that they are not limited to integers or even numbers in the input. We can pass character vectors, logical vectors, lists, or expressions.

``````rv <- letters[1:4]
for (i in rv) {
print(i)
}``````

#### Output

`````` "a"
 "b"
 "c"
 "d"``````

Let’s see another example.

``````# Create shows vector
shows <- c("Mandalorian", "Lacasa De Papel", "Expanse", "Friends")

# Create the for statement
for (show in shows) {
print(show)
}``````

In the above example, the loop iterates four times as the vector shows vector has four elements.

In each iteration, the show takes on the value of the corresponding item of shows.

## For Loop over a list

Looping over a list is just as easy and convenient as looping over a vector. Let’s see the following code example.

``````data <- list(Shares = c("Reliance", "TCS", "HDFC Bank", "HUL"))

for (i in data) {
print(data)
}``````

#### Output

``````\$Shares
 "Reliance" "TCS" "HDFC Bank" "HUL"``````

## For loop in data frame

To loop over a data frame, you need to create a data frame and then use for loop to iterate it.

``````name <- c("Donald", "Joe", "Hillary")
age <- c(74, 78, 65)
city <- c("New york", "Denver", "Dallas")

df <- data.frame(name, age, city)

for (i in names(df)) {
print(df[i])
}``````

#### Output

`````` name
1 Donald
2 Joe
3 Hillary
age
1 74
2 78
3 65
city
1 New york
2 Denver
3 Dallas``````

You can see that loop prints one by one column of the data frame using for loop.

## For loop with an increment in R

You can use the seq() function to increment value in each iteration of the for loop.

``````for (i in seq(0, 20, 5)) {
print(i)
}``````

#### Output

`````` 0
 5
 10
 15
 20``````

## Next statement in for loop

You can use the next statement in for loop when you want to skip the execution based on a specific condition, without stopping the entire loop’s execution.

``````for (i in seq(0, 20, 5)) {
if (i == 15) {
next
}
print(i)
}``````

#### Output

`````` 0
 5
 10
 20``````

## Nested For Loops in R

Nested for loop means the for loop inside another for loop. Suppose you want to manipulate a bi-dimensional array by setting its elements to specific values. Then you should consider nesting the for loop.

``````mtrx <- matrix(nrow = 30, ncol = 30)

# For each row and for each column, assign values
# based on position: product of two indexes
for (i in 1:dim(mtrx)) {
for (j in 1:dim(mtrx)) {
mtrx[i, j] = i * j
}
}

# Display the upper left 5x5 chunk
mtrx[1:5, 1:5]``````

#### Output

``````    [,1] [,2] [,3] [,4] [,5]
[1,]  1    2    3    4    5
[2,]  2    4    6    8   10
[3,]  3    6    9    12  15
[4,]  4    8    12   16  20
[5,]  5    10   15   20  25``````

You have two nested for loops in the code chunk above and thus two sets of curly braces, each with its own block and governed by its own index. That is, i run over the lines, and j runs over the columns.

## Conclusion

In this article, we have seen what a loop is and the type of loops in R. Then, we have seen for loop, its syntax, and flowchart. Then we have seen how to use for loop in the list, matrix, vector, and also nested loops.

Categories R