Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade Teachers Spaces Get Certified Upgrade Teachers Spaces
   ❮     
     ❯   

RWhile Loop


Loops

Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more readable.

R has two loop commands:

  • while loops
  • for loops

R While Loops

With thewhile loop we can execute a set of statements as long as a condition is TRUE:

Example

Printi as long asi is less than 6:

i <- 1
while (i < 6) {
  print(i)
  i <- i + 1
}
Try it Yourself »

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

Thewhile loop requires relevant variables to be ready, in this example we need to define an indexing variable,i, which we set to 1.

Note: remember to increment i, or else the loop will continue forever.


Break

With thebreak statement, we can stop the loop even if the while condition is TRUE:

Example

Exit the loop ifi is equal to 4.

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

The loop will stop at 3 because we have chosen to finish the loop by using thebreak statement wheni is equal to 4 (i == 4).



Next

With thenext statement, we can skip an iteration without terminating the loop:

Example

Skip the value of 3:

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

When the loop passes the value 3, it will skip it and continue to 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
}
Try it Yourself »

If the loop passes the values ranging from 1 to 5, it prints "No Yahtzee". Whenever it passes the value6, it prints "Yahtzee!".



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookies andprivacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.


[8]ページ先頭

©2009-2025 Movatter.jp