Explain For Loop in R programming language?

For loop in R Programming Language is useful to iterate over the elements of a list, data frame, vector, matrix, or any other object. It means, the for loop can be used to execute a group of statements repeatedly depending upon the number of elements in the object. It is an entry-controlled loop, in this loop the test condition is tested first, then the body of the loop is executed, the loop body would not be executed if the test condition is false.


for (var in vector) {

Example: Iterating over a range in R – For loop

# R Program to demonstrate
# the use of for loop
for (i in 1: 4)
    print(i ^ 2)


[1] 1
[1] 4
[1] 9
[1] 16

In the above example, we iterated over the range 1 to 4 which was our vector. Now there can be several variations of this general for loop. Instead of using a sequence 1:5, we can use the concatenate function as well.