Loops in R | R Programming

sanket-parate Trending Technology

A Loop statement allows repeating a specific statement or group of statements multiple times. In this article, you will learn to create different loops in R Programming:

• For Loop
• While Loop
• Repeat Loop

For Loop: It is used to iterate over a vector.

Flowchart of For Loop:


Syntax of For Loop:

For (val in sequence)
{
#statement
}

Here, the sequence is vector and val takes on each of its value during the execution of loop.
Example:

X<-c(1,2,3,4,5,6,7,8)
sum<-1
for( i in X)
{
sum=sum+i;
}
print(sum);

Output:
[1] 37

While Loop: It is used until a specific condition is met.
FlowChart of While Loop


Syntax of While Loop:

while (test_expression)
{
#statement
}
Here, test_expression is evaluated and the body of the while loop is entered if the result is TRUE. This is repeated each time until test_expression evaluates to FALSE.

Example:

X<-5
while(X< 10){
print(X)
X=X+1
}

Output:
[1] 5
[2] 6 
[3] 7
[4] 8
[5] 9

Repeat Loop: It is used to iterate over a block of code multiple number of times. To exit from this loop you have to use the break statement else it will result into an infinite loop.

FlowChart of Repeat Loop:

Syntax of Repeat Loop:

repeat{
#statement
}

Example:

Z<-2
repeat{ 
print(Z)
Z=Z+1
if(Z==10){
break;
}
}
 
Output:
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
 

Sanket Parate

Tech enthusiast and an optimistic guy with the mindset to achieve the set target. I am an avid learner and passionate learner. After finding my interest in data science, I felt that 'Yes this is the field which I am looking for. I am more passionate to learn data science and R and looking forward to exploring more in these fields along with the python. I love to share information with people.

Leave a Reply

Your email address will not be published. Required fields are marked *