EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

Loops in R

By Priya PedamkarPriya Pedamkar

Home » Data Science » Data Science Tutorials » R Programming Tutorial » Loops in R

Loops in R

What are loops in R?

Loops in R programming language are important features which are used to process multiple data elements for business logic. This is a generic programming logic supported by R language to process iterative R statements .R language supports several loops such as while loops, for loops, repeat loops. Loops help R programmers to implement complex logic while developing the code for the requirements of the repetitive step. These are syntax specific and support various uses cases in R programming. These are controlled by the loop condition check which determines the loop iterations, entry and exit of the loop scope.

Explain loops in R Programming?

R is a programming language used by data scientists, data miners for statistical analysis and reporting. They are an important concept to get a deeper understanding of R. To perform Monte Carlo methods in R loops are helpful. Especially for loops are helpful when it comes to simulation part – for example Markov chain process which uses a set of random variables. The state-space involves many finite loops at the origin. In machine learning models to save memory using generators is the key benefit. It is done by defining a function that loops over the elements it defines. In data science, the code duplication makes an impact on code mistakes. It is necessary to identify and remove duplicate values from the dataset. The tool used to reduce them is iteration which performs multiple sample input on different data sets. Therefore, it is necessary to use three iteration paradigms: for loops, repeat and while loops.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

1. For Loops in R

For loop works on many data structures like arrays, matrix, list, vectors. The basic syntax of For loop in R Programming is given below-

Syntax:

for ( i in 1:n)
{
Body of the statements
}
Nested For loops
for (i in 1: n)
{
for ( i in 1:n)
{
Body of the statements
}
}

Flow Diagram in For Loop

In the below diagram for each value in the sequence, the loop gets executed. when there is no more value it returns to exit.

Loops in R 1

Example:

Here is a simple example to print the numbers.

for (n in 1:6)
{
print (5 * n)
}

Popular Course in this category
R Programming Training (12 Courses, 20+ Projects)12 Online Courses | 20 Hands-on Projects | 116+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,998 ratings)
Course Price

View Course

Related Courses
Statistical Analysis Training (10 Courses, 5+ Projects)All in One Data Science Bundle (360+ Courses, 50+ projects)

Output:
5
10
15
20
25
30

To count the number of odd values in the list

a <- c (2,7,3,13,8,11,6)
ct <- 0
for (val in a) {
if (! val %% 2 == 0)
ct = ct+1
}
print(ct)

Output:

[1] 4

1. Nested for Loop

Example:

for (i in 1: 4)
{
for ( j in 1:3)
{
print (i*j)
}
}

Output:

1 2 3 2 4 6 3 6 9 4 8 12

2. For Loop using List

Example:

Creation of list using Three vectors

a <- list ("Sunday", "Monday", c (24,63,01), FALSE, 33.9, 12.6)
print (a)

Output:

[[1]] [1] “Sunday”
[[2]] [1] “Monday”
[[3]] [1] 24 36 1
[[4]] [1] False
[[5]] [1] 33.9
[[6]] [1] 12.6

3. Using Vector

x<- 1:6
y<- 1:6
tw <- numeric (length = length(x))
for (i in seq_along(x)) {
tw[i] <- x[i] + y[i] }
tw

Output:

2 4 6 8 10 12

The above program has three components:

  1. Assigning vector length(). It is necessary to allocate sufficient space to maintain efficiency. And the vector has a type of datatypes.
  2. Second, comes the sequence to determine indices for each element.
  3. The third is the body of the statements. This is the place where the code performs its work, it runs iteratively each time with a different value of i.

2. While Loop in R

The block of code is executed until the condition is false (Logical condition) which gives a comparison expression.

Syntax:

While (test condition)
{
Body of the statement
}

Flow Diagram in While Loop

Below diagram shows the flow diagram of while-loop in R.

Loops in R 2

Example:

Well, here is an example of a While loop. To compute the square of the number until 3.

i <- 1
while(i<=3)
{
print(i*i)
i=i+1
}

Output:

1
4
9

In the above example, it is clear that ‘i’ is declared initially 1 and the condition here is (i<3), checks for the true statement since 1 is less than 3. the body of the statement is executed and I value is incremented. The loop is executed until the condition is false and the while loop exits.

3. Repeat loops in R

This loop helps to execute the same code repeatedly until a stop condition is reached(break). Below flow diagram gives a clear workflow or repeat statement. At the start, it uses repeat keyword followed by the executable statements written inside the loop and if statements depict the constraint condition. And finally, the only way to terminate the loop is by the execution of break statements. It is an alternative of the do-while keyword of traditional programming (a reflection of it).

Syntax:

repeat
{
commands
if (condition expression) {
break}}

Flow Diagram

Block of statement

Example:

Let’s see an example for understanding the repeat statement

s  <- 1
repeat
{
s <- s+3;
print (s);
if (s>10)
break;
}

Output

4
7
10
13

Example:

s <- 0
repeat {
s = s+1
print(s)
if (s == 4) {
print (" ends");
break
}
}

Output:

1
2
3
4
“ends”

Conclusion

Now it is understood the basic concepts and examples of loops in R. To conclude, use of these reduces the time and memory saving and other controversial is loops are little slower in R. It is good if you try to put little code inside the loop and the use of repeat statement in R should be terminated with proper condition. And the use of it is preferred when an operation is to be repeated. After reading all the key points care should be taken during the implementation of R. To improve the performance of the loop avoid using the loop on the intensive objects. For loops are quite simple but should avoid them and use the vectorization concept which is better fast.

Recommended Articles

This has been a guide on loops in R. Here we have discussed the Concept, Type and Examples of Loops in R. You may also look at the following articles to learn more –

  1. Loops in C++ with Examples
  2. XGBoost Algorithm
  3. Introduction to While Loop in R
  4. Different Types of Loops in PowerShell
  5. Top 3 Types of Loops in Shell Scripting

R Programming Training (12 Courses, 20+ Projects)

12 Online Courses

20 Hands-on Projects

116+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
R programming Tutorial
  • Loops
    • Loops in R
    • For Loop in R
    • Nested For Loop in R
    • While Loop in R
    • Next in R
  • Basic
    • What is R Programming Language
    • Careers in R Programming
    • Install R
    • List of R Packages
    • Introduction of R Tools Technology
    • R Programming Language
    • What is RStudio?
    • R-studio-Functions
    • R Packages
    • R Data Types
    • R Operators
    • Vectors in R
  • Control statement
    • If Statement in R
    • If Else Statement in R
    • Else if in R
    • Switch Statement in R
  • Chart/graphs
    • Graphs in R
    • Bar Charts in R
    • Pie Chart in R
    • Histogram in R
    • Line Graph in R
    • Plot Function in R
    • Scatterplot in R
    • R Boxplot labels
  • Regression in R
    • Simple Linear Regression in R
    • Linear Regression in R
    • Multiple Linear Regression in R
    • Logistic Regression in R
    • Poisson Regression in R
    • OLS Regression in R
    • P-Value in Regression
  • Anova in R
    • ANOVA in R
    • One Way ANOVA in R
    • Two Way ANOVA in R
  • Data Structure
    • R list
    • Arrays in R
    • Data Frames in R
    • Factors in R
  • Advanced
    • Statistical Analysis with R
    • R String Functions
    • Data Exploration in R
    • R CSV Files
    • KNN Algorithm in R
    • Sorting in R
    • lm Function in R
    • Hierarchical Clustering in R
    • R Normal Distribution
    • Binomial Distribution in R
    • Decision Tree in R
    • GLM in R
    • Linear Model in R
    • Predict Function in R
    • Survival Analysis in R
    • Standard Deviation in R
    • Statistical Analysis in R
    • T-test in R
    • Database in R
  • Programs
    • R Program Functions
    • Factorial in R
    • Random Number Generator in R
  • Interview question
    • R Interview Questions

Related Courses

R Programming Certification Course

Statistical Analysis Course Training

All in One Data Science Courses

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - R Programming Training (12 Courses, 20+ Projects) Learn More