EDUCBA

EDUCBA

MENUMENU
  • Blog
  • Free Courses
  • All Courses
  • All in One Bundle
  • Login
Home Data Science Data Science Tutorials R Programming Tutorial Loops in R

Loops in R

By Priya PedamkarPriya Pedamkar

Loops-in-R

What are loops in R?

Loops in the R programming language are essential for processing multiple data elements for business logic. It is a generic programming logic supported by the R language to process iterative R statements. The R language supports several loops, such as while loops, for loops, and repeat loops. Loops help R programmers implement complex logic while developing code for the requirements of the repetitive step. These are syntax-specific and support various use 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 and data miners for statistical analysis and reporting. They are important for getting a deeper understanding of R. It is helpful to perform Monte Carlo methods in R loops, especially for loops in the simulation part—for example, the Markov chain process, which uses a set of random variables.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

The state space involves many finite loops at the origin. In machine learning models, saving memory using generators is the key benefit. It is done by defining a function that loops over the elements it defines. In data science, code duplication has 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 inputs on different data sets. Therefore, it is necessary to use three iteration paradigms: for loops, repeat, and while loops.

1. For Loops in R

For loop works on many data structures like arrays, matrix, lists, and 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

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

R

Example:

Here is a simple example to print the numbers.

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

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. Also, 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. Here, the code performs its work; it runs each time iteratively 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

The below diagram shows the flow diagram of the while-loop in R.

Loops-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), which checks for the true statement since 1 is less than 3. The body of the statement is executed, and the ‘I’ value is incremented. The loop is executed until the condition is false and the while loop exits.

3. Repeat loops in R

The loop helps to execute the code repeatedly until a stop condition is reached (break). The below flow diagram depicts a clear workflow or repeat statement. It uses a repeated keyword followed by the executable statements and if statements that depict the constraint condition. Finally, executing break statements is the only way to terminate the loop. It is an alternative to the do-while keyword of traditional programming.

Syntax:

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

Flow Diagram

Loops-3

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

The basic concepts and examples of loops are understood in R. Using them reduces time and saves memory. A contention is that loops are a bit slower in R. It would be apt if you type some code inside the loop, and the repeat statements in R should be appropriately terminated. Its use is preferred when an operation is to be repeated. After reading all the key points, caution should be exercised during the implementation of R. To improve the performance of the loop, avoid using the loop on intensive objects. Loops are quite simple, but we should avoid them and use the faster vectorization concept.

Recommended Articles

The above is a guide on loops in R. Please check out the following articles to better understand other related concepts:

  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
All in One Excel VBA Bundle
500+ Hours of HD Videos
15 Learning Paths
120+ Courses
Verifiable Certificate of Completion
Lifetime Access
Financial Analyst Masters Training Program
1000+ Hours of HD Videos
43 Learning Paths
250+ Courses
Verifiable Certificate of Completion
Lifetime Access
All in One Data Science Bundle
1500+ Hour of HD Videos
80 Learning Paths
360+ Courses
Verifiable Certificate of Completion
Lifetime Access
All in One Software Development Bundle
3000+ Hours of HD Videos
149 Learning Paths
600+ Courses
Verifiable Certificate of Completion
Lifetime Access
Primary Sidebar
All in One Data Science Bundle1500+ Hour of HD Videos | 80 Learning Paths | 360+ Courses | Verifiable Certificate of Completion | Lifetime Access
Financial Analyst Masters Training Program1000+ Hours of HD Videos | 43 Learning Paths | 250+ Courses | Verifiable Certificate of Completion | Lifetime Access
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • 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

ISO 10004:2018 & ISO 9001:2015 Certified

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

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

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

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

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

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

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

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more