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 any programming language, For loop iterates over a sequence of items or values and executes 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 it is as follows.
- Repeat the execution for a given number of times.
- Access and manipulate the vector, Matrix, or Data Frame elements.
- To Perform calculations. For instance, calculate the sum of a numeric sequence, average, factorial, etc.
- To generate a formula based pattern or series of values.
R For Loop Syntax
It 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 a 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 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 example 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 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 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 ---")
for loop Initialization Example
In the example below, 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 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 example below starts at 1, increments variable i by 2, and prints every alternative number from 1 to 10.
for (i in seq(1, 10, by = 2)) { print(i) }
[1] 1
[1] 3
[1] 5
[1] 7
[1] 9
Decrement Example
The below for loop program code starts at 10, decrements i variable by 2 (by = -2), and prints every alternative number from 10 to 2.
for (i in seq(10, 1, by = -2)) { print(i) }
[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 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 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 exits.
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 ---")
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, 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
- 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.
In the 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 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. This example prints multiplication tables up to 5. Here, the outer (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") } cat("\n") }
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 for loop becomes more powerful when you combine conditional statements like if condition and if else inside it.
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 example below, the for loop iterates 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 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) { next } print(i) }
[1] 2
[1] 4
[1] 6
[1] 8
[1] 10
For loop break statement Example
The 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) { break } print(i) }
[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 to access and update or manipulate the matrix items. Because nested For Loops help 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 programming language 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) print(mat) for (i in 1:nrow(mat)) { for (j in 1:ncol(mat)) { cat(i, ",", j, " = ", mat[i, j], "\t") } cat("\n") }
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 iterates 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 } print(sum)
[1] 180
How to use for loop to access Data frame rows and columns?
Using the For Loop, 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") cat("\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 Loops
- Ensure that the start and end conditions are set correctly.
- Avoid infinite loops by providing appropriate termination conditions.
- Always check the step argument sign of the seq() function.
- Avoid using them for complex operations.
- Instead of a for loop, utilize the vectorized functions that efficiently perform operations on entire vectors or matrices.