Flowchart of For loop in R

For loop in R

Iterating over a range in R – For loop

R




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


Output: 

[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.

Using concatenate function in R – For loop

R




# R Program to demonstrate the use of
# for loop along with concatenate
for (i in c(-8, 9, 11, 45))
{
    print(i)
}


Output: 

[1] -8
[1] 9
[1] 11
[1] 45

Instead of writing our vector inside the loop, we can also define it beforehand.

Using concatenate outside the loop R – For loop

R




# R Program to demonstrate the use of
# for loop with vector
x <- c(-8, 9, 11, 45)
for (i in x)
{
    print(i)
}


Output: 

[1] -8
[1] 9
[1] 11
[1] 45

For loop in R

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.

Similar Reads

For loop in R Syntax:

for (var in vector) { statement(s) }...

Flowchart of For loop in R:

For loop in R...

Nested For-loop in R

...

Jump Statements in R

...

Creating Multiple Plots within for-Loop in R

...

Contact Us