In this tutorial you will learn about the R for loop and its application with practical example.
R for loop
The for in loop takes a list or collection of data(list, data frame, vector, matrix , or anything that provides an iterator) and iterate through the its elements one at a time in sequence.
Swift For In Loop Flow Diagram
Syntax:-
1 2 3 4 |
for (item in items) { // loop body } |
Here, items is a vector that allows us to fetch each of the single element, and item hold the the current element fetched from the items.
Iterating over a Vector using for loop
In R, we can loop over a vector using for loop as following –
Example:-
1 2 3 4 5 |
employees <- c('John', 'Keith', 'Alex', 'Jason') for (emp in employees) { print(emp) } |
Here, we have initialized a vector employees with 4 elements and then loop over it using for loop. When we run the above R script, we see the following output –
Output:-
Iterating over a list using for loop
In R, we can loop over a list using for loop as following –
Example:-
1 2 3 4 5 6 |
employees <- list(empName = c('John', 'Keith', 'Alex', 'Jason'), empAge = c(25, 30, 35, 25), empSalary = c(5000, 10000, 8000, 6000), empDept = 'Sales') for (emp in employees) { print(emp) } |
Here, we have created a list employees with four vectors empName, empAge, empSalary and empDept. Next, we are iterating over it.
When we run the above R script, we see the following output –
Output:-
Iterating over a matrix using for loop
In R, we can loop over a matrix using for loop as following –
Example:-
1 2 3 4 |
mat <- matrix(data = seq(1, 10, by=1), nrow = 5, ncol =2) for (r in 1:nrow(mat)) for (c in 1:ncol(mat)) print(paste("Row", r, "and column",c, "have values of", mat[r,c])) |
Here, we have [5,2] matrix with 5 row 2 columns. In order to iterating over its elements we would need two for loops, one for rows and another one for columns.
Output:-