R For Loop

R for loop is used to repeat a sequence of instructions in certain conditions. It permits us to run automatically of our code which needs repetition. In Short, for loop is an iterate control structure. It allows us to easily write the loop that needs to run a particular number of times.

For loop can be defined in R language as:

  • It begins with the keyword for like C++ language.
  • Rather than, initializing and declaring a loop counter variable, we declare a variable which is of the same type as the base type of matrix, vector, etc. with a colon which is followed by the array of matrix name.
  • In the body of loop, use the loop variable instead of using indexed array element.

Have a look at the syntax of R for loop:

Flowchart of R For Loop

R For Loop
Flowchart of R For Loop

The following code will print all values of a given vector.

languages <- c("Python", "R", "Java", "C++", "Ruby", "HTML")

for ( i in languages){   
    print(i)  
}  

Output:

f1

The following code will print the values of a list.

l <- c()  
 
for (i in seq(4, 12, by=1)) {  
  l[[i]] <- i*i  
}  
print(l)  

Output:

f2 1

The following code will print the values of a matrix.

m<- matrix(data = seq(5, 12, by=1), nrow = 8, ncol =2)  

for (r in 1:nrow(m))     
    for (c in 1:ncol(m))    
         print(paste("m[", r, ",",c, "]=", m[r,c]))   
print(m)  

Output:

f3 1