R While Loops


Loops

Loops can create a code block as long as the specified condition is reached.

Loops work because they save time, reduce errors, and make the code more readable.

R has two loop commands:

  • while loops
  • for loops


R While Loops

With a while loop we can make a set of statements as long as the condition is TRUE:

Example

Print i as long as i is less than 6:

i <- 1
while (i < 6) {
  print(i)
  i <- i + 1
}

In the example above, the loop will continue to generate numbers from 1 to 5. The loop will stop at 6 because 6 < 6 is FALSE.

The loop while it needs a variable that is right for you, in this example we need to define the variable variable, i, which we have set in 1.

Note: remember to increment i, otherwise the loop will continue permanently.



Break

With a break statement, we can stop the loop even if the situation says TRUE:

Example

Exit the loop if i is equal to 4.

i <- 1
while (i < 6) {
  print(i)
  i <- i + 1
  if (i == 4) {
    break
  }
}

The loop will stop at 3 because we have chosen to end the loop using the break statement when i is equal to 4 (i == 4).



Next

With the next statement, we can skip repeats without breaking the loop:

Example

Skip the value of 3:

i <- 0
while (i < 6) {
  i <- i + 1
  if (i == 3) {
    next
  }
  print(i)
}

If the loop exceeds 3 loops, it will skip and continue loop.



Yahtzee!

If .. Else Combined with a While Loop

To demonstrate a practical example, let us say we play a game of Yahtzee!

Example

Print "Yahtzee!" If the dice number is 6:

dice <- 1
while (dice <= 6) {
  if (dice < 6) {
    print("No Yahtzee")
  } else {
    print("Yahtzee!")
  }
  dice <- dice + 1
}

If the loop exceeds the range from 1 to 5, it prints "No Yahtzee". Whenever it exceeds 6, it prints "Yahtzee!".