R Loops
Loops are used to repeat a certain set of actions so you don’t have to perform them repeatedly. Suppose you want to perform operation 10 times, if you start writing the code for each time, the program’s length increases and it would be difficult for you to understand it later. But you can remove this problem by using a loop, by writing the same statement inside a loop; it will save time and makes easier for code reliability.
R language has the following kinds of a loop:
Repeat
Repeat loop is used to execute the same block of code again and again until a stop condition is met.
Syntax:
repeat { commands if(condition) { break } }
Flow Chart:
Example:
x <- 1 repeat { print(x) x = x+1 if (x == 6){ break } }
Output:
[1] 1 [1] 2 [1] 3 [1] 4 [1] 5
While loop
While loop is also used to execute the same block of code again and again until a break condition is met.
Syntax:
while (test_expression) { statement }
Flow Chart:
Example:
i <- 1 while (i < 10) { print(i) i = i+1 }
Output:
[1] 1 [1] 2 [1] 3 [1] 4 [1] 5 [1] 6 [1] 7 [1] 8 [1] 9
The main difference between repeat and while loop is that while tests a condition to define when to finish looping, but repeat requires you to explicitly break the loop on your own and which can be at any point in the body of the loop. Depending on where you put your break statement.
For loop
For loop is used to iterate over a list of elements or a range of numbers. Loop can be used to iterate over a data frame, vector, list, matrix or any other object.
Syntax:
for (value in vector) { statements }
Flow Chart:
Example:
student <- c('Nikita', 'Nidhi', 'Deep', 'Aman') for ( i in student){ print(i) }
Output:
[1] "Nikita" [1] "Nidhi" [1] "Deep" [1] "Aman"
Break Statement
In R programming language break statement has the following two usages:
- The break statement is used to terminate the program and resumes the control to the next statement following the loop.
- The break is also used to terminate a case in the switch statement.
Syntax:
break
Flow Chart:
Example 1:
# R for loop a = c(20, 14, 10, 18) print("break in for loop") for(i in a) { if(i==10){ break } print(i) }
Output:
[1] 20 [1] 14
Example 2:
# R while loop a = 1 b = 4 print("break in while loop") while(a<5) { print(a) a = a+1 if(b+a >6){ break } }
Output:
[1] 1 [1] 2
Next Statement
A next statement is used to skip the current iteration of the loop without terminating it. It is similar to continue statement in other programming languages.
Syntax:
next
Flow Chart:
Example 1:
for(i in 1:10) { if((i%%2)==0) { next } print(i) }
Output:
[1] 1 [1] 3 [1] 5 [1] 7 [1] 9
Example 2:
v <- LETTERS[1:6] for ( i in v) { if (i == "C") { next } print(i) }
Output:
[1] "A" [1] "B" [1] "D" [1] "E" [1] "F"