R For Loop

This article helps you understand the significance and benefits of the R for loop by starting with the syntax and a simple example. Next, we cover the nested for loops and some real-world problems. After reading this article, you should understand the For Loop in R programming and how to use it effectively in your daily tasks.

In R programming language, For loop iterate over a sequence of items or values and execute the code repeatedly. For instance, perform a simple calculation on a vector. The simple one line syntax of the for loop in R improves the readability and maintainability. In addition, it reduces the amount of code required to perform a repetitive task.

The R For Loop’s ability to iterate over different data structures and perform tasks repeatedly makes it a valuable tool in data analysis, scientific computing, etc. However, it would be best to be careful when dealing with large datasets.

The most common uses of the R for loop is as follows.

  1. Repeat the execution for a given number of times.
  2. Access and manipulate the vector, Matrix, or Data Frame elements.
  3. To Perform calculations. For instance, calculate the sum of a numeric sequence, average, factorial, etc.
  4. To generate a formula based pattern or series of values.

R For Loop Syntax

The R for loop repeats a block of statements until there are no items in the vector. It follows a specific syntax that includes initialization, condition, and incrementing initialized components. The basic syntax of the for loop in R programming language is.

for(val in vector)  {
     Statement 1
     Statement 2
     Statement N

If you observe the above syntax of R for loop, the Vector may be a string, integer, or anything you want to iterate.

  • It starts with an Object, which means it will iterate a Vector and assign the first item to a value. For example, values are A: E, assigning A to val.
  • Next, it will execute the statements inside the R For loop.
  • After completing the statements, it will go to the vector and assign the following value to the val.
  • The process will be repeated until there are no items.

For Loop in R Programming Flow Chart

The screenshot below will show you the flow chart behind the For Loop.


R For Loop Example

This for loop in R programming example, we will explain this working functionality on integer. In this example, num is the initialization component, and 1:10 is the sequence. The program will initialize the num variable to the first value in the 1:10 seq, i.e., 1.

Next, the R for loop will iterate over the sequence and multiply each number by 9 until the num variable reaches 10 (Less than or equal to 10). After each loop iteration, the num variable incremented to the next value in the sequence, i.,e, 2, 3, 4, 5, 6, 7, 8, 9, 10.

numbers <- c(1:10)

for (num in numbers) {
  print(9 * num)
print("---- This is Coming from Outside ---")
R For Loop 2

Initialization Example

In the below example, we have initialized i as 0 at the beginning of the code or before the for loop begins. However, the R for loop will override i variable and reassign it to the sequence’s first value, i.e., 3.

i <- 0

for (i in 3:5) {
  print(5 * i)
[1] 15
[1] 20
[1] 25

Increment Example

Instead of using the colon operator, we can use the seq() function in R for loop to generate the sequence of numbers. The seq() function has a step argument that allows you to add the step size or increment the initialized variable.

The below example starts at 1, increments i variable by 2, and prints every alternative number from 1 to 10.

for (i in seq(1, 10, by = 2)) {
[1] 1
[1] 3
[1] 5
[1] 7
[1] 9

Decrement Example

The below R for loop program code starts at 10, decrement i variable by 2 (by = -2), and prints every alternative number from 10 to 2.

for (i in seq(10, 1, by = -2)) {
[1] 10
[1] 8
[1] 6
[1] 4
[1] 2

R For Loop to Iterate over a range of Strings

This example will explain how this R for loop extracts individual items or data from a Vector. In this R Programming example, we declared Countries and assigned the following values.

Here, we used the R for loop to iterate through the Countries vector and display each item. In the next line, we used a print statement outside of it. This statement will be executed once the compiler exit.

countries <- c('India', 'U K', 'Japan', 'U S A', 'Australia', 'China')

for (str in countries) {
  print(paste("Countries are:  ", str))
print("----This is Coming from Outside ---")
R For Loop 1

From the above Screenshot, you can observe that we used the Countries List in the second for Loop in R example code.

countries <- c('India', 'U K', 'Japan', 'U S A', 'Australia', 'China')

First Iteration

  • First Iteration, Country = ‘India’.
  • It means some items are in the vector so that it will execute the print statement inside the loop.

Second Iteration

  • In the second Iteration of the for loop, Country = ‘U K’.
  • It means some items are in the vector so that it will execute the print inside it.

Third Iteration

  • Country = ‘Japan’.
  • It means there are some items, so it executes the statement.

Fourth Iteration

  • Country = ‘U S A’.
  • It means some items are in the vector, so it executes the print statement.

Fifth Iteration of an R For Loop

  • Country = ‘Australia’, condition tested.
  • It means some items exist, so it executes the print statement.

Sixth Iteration

  • Country = ‘China’.
  • It means there are some items in the vector that will compile the print statement inside it.

Next iteration, there are no items in this to assign to the Country variable. So, it will exit.

Nested For loops in R Programming

The R programming language allows you to nest one loop inside another to iterate multi-level data (arrays, Matrix, data frames, etc.). The inner loop will entirely execute for each iteration of the outer or master loop. Because of this nested approach, you can perform more complex iterations and access multi-layered information.

Let me write a multiplication table program so that you understand the Nested For loops in R programming. This example prints multiplication tables up to 5. Here, the outer loop (for (i in 1:10)) iterates from 1 to 10, and the inner loop iterates from 1 to 5.

for (i in 1:10) {
 for (j in 1:5) {
  result <- i * j
  cat(result, "\t")
1 	2 	3 	4 	5 	
2 	4 	6 	8 	10 	
3 	6 	9 	12 	15 	
4 	8 	12 	16 	20 	
5 	10 	15 	20 	25 	
6 	12 	18 	24 	30 	
7 	14 	21 	28 	35 	
8 	16 	24 	32 	40 	
9 	18 	27 	36 	45 	
10 	20 	30 	40 	50 

The following section covers the practical example of the nested for loops to work with the Matrix.

If else statements within the R For loop

The R for loop becomes more powerful when you combine conditional statements like if condition and if else inside the loop.

To check the specific condition, you can include If Else statements within the For Loop. Based on the result, we can control the execution flow. By this, you can perform different actions.

In the below example, the R for loop iterate from 1 to 10. The if condition checks whether the remainder of the number divided by two equals zero. If True, print that as even; otherwise, print it as an odd number.

for (i in 10:15) {
 if (i %% 2 == 0) {
  print(paste(i, "is Even"))
 } else {
  print(paste(i, "is Odd"))
[1] "10 is Even"
[1] "11 is Odd"
[1] "12 is Even"
[1] "13 is Odd"
[1] "14 is Even"
[1] "15 is Odd"

Controlling the R For Loop with break and next Statements

We can use either of the two statements to manipulate the for loop execution flow.

For loop next statement Example

The R next statement is helpful when skipping some for loop iterations based on certain conditions because it skips the code in the current iteration and proceeds to the next one.

In this example, if i %%2 is not equal to 0, the next statement will skip the iteration that includes the print() and go to the next iteration.

for (i in 1:10) {
 if (i %%2 != 0) {
[1] 2
[1] 4
[1] 6
[1] 8
[1] 10

For loop break statement Example

The R break statement is helpful to exit or terminate the for loop based on a specific condition. For example, stopping the entire iteration process when the expression is true is beneficial.

for (i in 1:5) {
 if (i == 3) {
[1] 1
[1] 2

R For Loop to Iterate over Vectors, Matrices, and Data Frames

The following examples help you understand how to use the for loop to iterate the elements and Print the output.

For Loop to access Matrix rows and columns

We need the nested for loop in R programming language to access, and update manipulate the matrix items. Because nested For Loops helps to iterate over each row and column of a matrix to perform row-wise or column-wise operations.

A matrix has rows and columns; the nested For Loop in R iterates over each row and, within each row, iterates over each column of the row. Let me show you an example of the Matrix to understand.

We declared a 3 * 4 matrix of numbers from 1 to 12. The outer loop iterates over the row indices (3 times), and the inner loop iterates over the column indices (4 times). By using the index position matrix[i, j], we are accessing the individual elements of the Matrix.

mat <- matrix(c(1:12), 3, 4)

for (i in 1:nrow(mat)) {
 for (j in 1:ncol(mat)) {
  cat(i, ",", j, " = ", mat[i, j], "\t")
1 , 1  =  1 	1 , 2  =  4 	1 , 3  =  7 	1 , 4  =  10 	
2 , 1  =  2 	2 , 2  =  5 	2 , 3  =  8 	2 , 4  =  11 	
3 , 1  =  3 	3 , 2  =  6 	3 , 3  =  9 	3 , 4  =  12 

How to use for loop to access Vector Items?

You can iterate over each vector element using the R For Loop and access or manipulate it as needed. Although we can perform complex calculations, we provide a simple example so you can understand better.

In this example, we declared a numbers vector and sum variable. Next, the for loop iterate each vector element from 5 to 40. Finally, inside the loop (sum <- sum + n), we add a vector item to the sum variable to calculate the sum of all items.

numbers <- c(5, 10, 15, 20, 25, 30, 35, 40)
sum <- 0

for (n in numbers) {
 sum <- sum + n

[1] 180

How to use for loop to access Data frame rows and columns?

Using the For Loop in R, you can iterate over data frame rows and columns, access and manipulate data, apply functions, etc.

employee <- data.frame(Id = c(1:5),
Name = c("John", "Rob", "Christy", "Johnson", "Miller"),
Occupation = c("Professional", "Management", "Developer", "Programmer", "Admin"),
Salary = c(80000, 90000, 75000, 92000, 82000))

for (i in 1:nrow(employee)) {
 ID <- employee$Id[i]
 Name <- employee$Name[i]
 Occupation <- employee$Occupation[i]
 Salary <- employee$Salary[i]
 cat("ID:", ID, "\n")
 cat("Name:", Name, "\n")
 cat("Age:", Occupation, "\n")
 cat("Country:", Salary, "\n")
ID: 1 
Name: John 
Age: Professional 
Country: 80000 

ID: 2 
Name: Rob 
Age: Management 
Country: 90000 

ID: 3 
Name: Christy 
Age: Developer 
Country: 75000 

ID: 4 
Name: Johnson 
Age: Programmer 
Country: 92000 

ID: 5 
Name: Miller 
Age: Admin 
Country: 82000 

Best Practices and Tips of for loop

  1. Ensure that the start and end conditions are set correctly.
  2. Avoid infinite loops by providing appropriate termination conditions.
  3. Always check the step argument sign of the seq() function.
  4. Avoid using loops for complex operations.
  5. Instead of R for loop, utilize the vectorized functions that efficiently perform operations on entire vectors or matrices.