Loops in R (Chapter 1 Episode 6)

There are three kinds of loop in R:

  • repeat loop

  • while loop

  • for loop

repeat loop

The repeat loop runs as long as a condition is satisfied and it does not find a stop clause. You need to. explicitly add the condition inside the loop and use break to exit out of the loop.

syntax

repeat { 
commands 
if(condition) {
 break } }

If we want to print "Hello", "World" 4 times, we would have something like:

msg <- c("Hello","World!") 
count <- 2 
repeat { print(msg)
count <- count+1 
if(count > 5) { 
break } 
}

output

[1] "Hello"  "World!"
[1] "Hello"  "World!"
[1] "Hello"  "World!"
[1] "Hello"  "World!"

The count started at 2 and ends at mark of 5. The loop increased by 1 on the successful completion of an iteration , so "Hello","World" got printed 4 times.

y <- 1 
repeat { print(y) 
y = y+1 
if (y == 5){break}}

output

[1] 1
[1] 2
[1] 3
[1] 4

We initiated the value of y to be 1. In the if condition, if are checking for the value of y to be 5, at which the loop should stop.

while loop

In this type of loop, the code will be executed until a particular condition is met. If there is no condition to be met, the loop becomes infinite.

syntax

msg <- c("Hello","this is a while loop") 
count <- 2 
while (count < 6) {
print(msg)
count = count + 1 }

output

[1] "Hello"                "this is a while loop"
[1] "Hello"                "this is a while loop"
[1] "Hello"                "this is a while loop"
[1] "Hello"                "this is a while loop"

for loop

In this loop, a particular section of your code is executed for a specific number of times.

syntax

l <- LETTERS[1:5] 
for ( j in l) { 
  print(j) 
}

The variable i stores alphabet (A to E), we then used a for loop to iterate over each of them.

Loop control statement

The purpose of a loop control statement is to change the execution of a loop from its normal sequence.

break statement

  • The break statement is used to immediately terminate the program.
  • We can also use a break statement to terminate a case contained in a switch statement.
msg <- c("Hello","World!") 
count <- 2 
repeat { print(msg) 
  count <- count + 1 
  if(count > 6) 
    {break } }

output

[1] "Hello"  "World!"
[1] "Hello"  "World!"
[1] "Hello"  "World!"
[1] "Hello"  "World!"
[1] "Hello"  "World!"

In this program, the code was executed until the count was 6.

next statement

The next statement skips the current iteration of the loop and continue to the next iteration without terminating the loop.


l <- LETTERS[1:6] 
for ( j in l) 
{ if (j == "C") 
{ next }
  print(j) }

output

[1] "A"
[1] "B"
[1] "D"
[1] "E"
[1] "F"

The variable i was created to store the first 6 letters of the alphabet in uppercase. We have used to if statement to check when the iteration reaches C. At this point, the loop should skip to the next iteration.