R While 循环及其编程示例
⚡ 智能摘要
在 R 语言中,while 循环会重复执行一段代码,只要其条件为真(TRUE)。每次循环之前都会检查条件,因此循环体可能根本不会执行,而循环体内部的某些代码最终必须使条件变为假(FALSE)。

R 编程中的 While 循环
A while循环 在 R 语言中,只要条件为真,就会重复执行一段代码。该条件会被测试。 before 每次循环,因此如果条件从一开始就为 FALSE,则 while 循环可以运行零次。
R 中的 While 循环语法
以下是 R 编程中 While 循环的语法:
while (condition) {
Exp
}
R While 循环流程图

注意:循环内部的某些操作最终必须使条件为假。否则,循环将无限运行,您必须使用 Esc 或 Ctrl+C 中断 R 操作。
R语言中的while循环、for循环和repeat循环。
R 提供三个厕所ping 构造函数有很多种,而选择哪一种取决于你是否事先知道需要多少次迭代。
| 标准 | 而 | HPMC胶囊 | 重复 |
|---|---|---|---|
| 迭代次数 | 事先未知 | 事先知道 | 事先未知 |
| 测试条件 | 每次传球前 | 序列已用尽 | 永远不要,你必须喊“休息”。 |
| 最低运行次数 | 零 | 零 | 一个 |
| 典型用途 | 收敛于阈值 | 遍历向量或列表 | Do while 风格逻辑 |
| 句法 | while (cond) { } | for (i in v) { } | 重复 { … 中断 } |
# repeat always runs at least once count <- 1 repeat { print(count) count <- count + 1 if (count > 5) break }
上面的股票例子很贴切:你无法预先知道价格跌到 45 之前需要多少次随机抽取。
R 语言中的 while 循环示例
例子1
从最简单的开始 R编程 例如,你创建一个计数器,每次循环都加 1。循环必须能够结束,因此条件明确地告诉 R,当变量超过 10 时停止循环。
注意::如果要查看当前循环值,则需要将变量包装在函数 print() 内。
#Create a variable with value 1 begin <- 1 #Create the loop while (begin <= 10){ #See which loop we are on cat('This is loop number', begin, '\n') #add 1 to the variable begin after each loop begin <- begin+1 print(begin) }
输出:
## This is loop number 1[1] 2 ## This is loop number 2[1] 3 ## This is loop number 3[1] 4 ## This is loop number 4[1] 5 ## This is loop number 5[1] 6 ## This is loop number 6[1] 7 ## This is loop number 7[1] 8 ## This is loop number 8[1] 9 ## This is loop number 9[1] 10 ## This is loop number 10[1] 11
例子2
假设你以 50 美元的价格买入了一只股票。如果价格跌到 45 美元或以下,你想做空它,否则继续持有。循环的每次迭代都会使价格在 50 美元附近随机上下波动最多 10 美元:
set.seed(123) # Set variable stock and price stock <- 50 price <- 50 # Loop variable counts the number of loops loop <- 1 # Set the while statement while (price > 45){ # Create a random price between 40 and 60 price <- stock + sample(-10:10, 1) # Count the number of loop loop <- loop + 1 # Print the number of loop print(loop) }
输出:
## [1] 2 ## [1] 3 ## [1] 4 ## [1] 5 ## [1] 6 ## [1] 7
cat('it took',loop,'loop before we short the price. The lowest price is',price)
输出:
## it took 7 loop before we short the price. The lowest price is 40
如何在 While 循环中使用 break 和 next
两个关键词改变了任何 R 循环的正常流程。
- 打破 立即退出循环,跳过ping 剩余的每一次迭代。
- 下页 仅放弃当前迭代,直接跳转到下一个条件测试。
# break: stop as soon as a condition is met i <- 1 while (i <= 100) { if (i * i > 50) { cat('First square above 50 is', i * i, '\n') break } i <- i + 1 } # next: skip the even numbers i <- 0 while (i < 10) { i <- i + 1 if (i %% 2 == 0) next print(i) }
一个值得了解的陷阱。 在 while 循环中,`next` 会跳转回条件测试。 也完全不需要 运行它下面的任何内容。如果计数器在循环体底部递增,则 `next` 会跳过该递增操作,导致循环永远阻塞。这就是为什么第二个示例递增的原因。 before 是下一句,而不是它之后的一句。
常见的while循环错误和无限循环
几乎所有失败的while循环都归因于以下四个错误。
- 计数器从未更新。 忘记递增参数会导致条件永久为真。在 RStudio 中按 Esc 键,或在终端中按 Ctrl+C 键可中断操作。
- 该条件返回 NA。 如果测试中的任何值为 NA,R 会停止运行并显示“此处缺少 TRUE/FALSE 值”。可以使用 is.na() 或 isTRUE() 来保护它。
- 该条件包含多个元素。 自 R 4.2 版本起,长度大于 1 的条件语句会被视为错误而非警告。请将其包裹在 any() 或 all() 函数中。
- 浮点数比较永远不会变为 FALSE。 while (x != 0.3) 可能会无限循环,因为 0.1 + 0.2 不等于 0.3。改用容差进行比较,例如 abs(x – 0.3) > 1e-8。
# Safety valve: cap the number of iterations iter <- 0 while (price > 45 && iter < 1000) { price <- stock + sample(-10:10, 1) iter <- iter + 1 }
对于任何退出依赖于随机或外部数据的循环来说,添加最大迭代次数是一种廉价的保险措施。
