R For 循环
For 循环
for 循环用于迭代序列:
实例
for (x in 1:10) {
print(x)
}
这不太像其他编程语言中的 for 关键字,而更像其他面向对象编程语言中的迭代器方法。
使用 for 循环,我们可以对向量、数组、列表等中的每个项目执行一组语句。
实例
打印列表中的每个项目:
fruits <- list("apple", "banana", "cherry")
for (x in fruits) {
print(x)
}
实例
打印骰子的数量:
dice <- c(1, 2, 3, 4, 5, 6)
for (x in dice) {
print(x)
}
提示:for 循环不需要像 while 循环那样预先设置索引变量。
Break
使用 break 语句,我们可以在它遍历所有项目之前停止循环:
实例
在 "cherry" 处停止循环:
fruits <- list("apple", "banana", "cherry")
for (x in fruits) {
if (x == "cherry") {
break
}
print(x)
}
循环将在 "cherry" 处停止,因为我们选择在 x 等于 "cherry"(x == "cherry")时使用 break 语句来完成循环。
Next
使用 next 语句,我们可以在不终止循环的情况下跳过一次迭代:
实例
跳过 "banana":
fruits <- list("apple", "banana", "cherry")
for (x in fruits) {
if (x == "banana") {
next
}
print(x)
}
当循环传递 "banana" 时,它将跳过并继续循环。
If .. Else 与 For 循环组合
为了演示一个实际的例子,假设我们玩 Yahtzee 游戏!
实例
如果骰子数是 6,则打印 "Yahtzee!":
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"))
}
}
如果循环达到从 1 到 5 的值,它将打印 "No Yahtzee" 和其数字。 当它达到值 6 时,它会打印 "Yahtzee!" 和其数字。