選單
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

R For Loop


For 迴圈

A for loop is used for iterating over a sequence

示例

for (x in 1:10) {
  print(x)
}
自己動手試一試 »

This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-oriented programming languages.

With the for loop we can execute a set of statements, once for each item in a vector, array, list, etc..

You will learn about lists and vectors, etc in a later chapter.

示例

Print every item in a list

fruits <- list("apple", "banana", "cherry")

for (x in fruits) {
  print(x)
}
自己動手試一試 »

示例

Print the number of dices

dice <- c(1, 2, 3, 4, 5, 6)

for (x in dice) {
  print(x)
}
自己動手試一試 »

The for loop does not require an indexing variable to set beforehand, like with while loops.


Break

With the break statement, we can stop the loop before it has looped through all the items

示例

Stop the loop at "cherry"

fruits <- list("apple", "banana", "cherry")

for (x in fruits) {
  if (x == "cherry") {
    break
  }
  print(x)
}
自己動手試一試 »

The loop will stop at "cherry" because we have chosen to finish the loop by using the break statement when x is equal to "cherry" (x == "cherry").



下一步

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

示例

Skip "banana"

fruits <- list("apple", "banana", "cherry")

for (x in fruits) {
  if (x == "banana") {
    next
  }
  print(x)
}
自己動手試一試 »

When the loop passes "banana", it will skip it and continue to loop.


Yahtzee!

If .. Else Combined with a For Loop

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

示例

Print "Yahtzee!" If the dice number is 6

dice <- 1:6

for(x in dice) {
  if (x == 6) {
    print(paste("The dice number is", x, "Yahtzee!"))
  } else {
    print(paste("The dice number is", x, "Not Yahtzee"))
  }
}
自己動手試一試 »

If the loop reaches the values ranging from 1 to 5, it prints "No Yahtzee" and its number. When it reaches the value 6, it prints "Yahtzee!" and its number.



×

聯絡銷售

如果您想將 W3Schools 服務用於教育機構、團隊或企業,請傳送電子郵件給我們
sales@w3schools.com

報告錯誤

如果您想報告錯誤,或想提出建議,請傳送電子郵件給我們
help@w3schools.com

W3Schools 經過最佳化,旨在方便學習和培訓。示例可能經過簡化,以提高閱讀和學習體驗。教程、參考資料和示例會不斷審查,以避免錯誤,但我們無法保證所有內容的完全正確性。使用 W3Schools 即表示您已閱讀並接受我們的使用條款Cookie 和隱私政策

版權所有 1999-2024 Refsnes Data。保留所有權利。W3Schools 由 W3.CSS 提供支援