参考资料:学习R
在R中有三种循环:repeat、while和for。虽然向量化意味着我们可能并不需要大量使用它们,但在需要重复执行代码时,它们是非常有用的。
1、重复循环
R中最容易掌握的循环是repeat。它所做的事情就是反复地执行代码,直到告诉它停为止。下面这个代码将反复执行,直到我们按下escape键、退出R为止。
R
repeat{
message("Happy Groundhog Day!")
}
一般来说无限循环不是我们想要的,因此需要一个break语句来跳出无限循环。下例中,sample函数将在每个循环迭代中返回一个操作:
R
repeat{
message("Happy Groundhog Day!")
action<-sample(
c(
"Learn French",
"Make an ice status",
"Rob a bank",
"Win heart of Andie McDowell"
),
1
)
message("action= ", action)
if(action=="Win heart of Andie McDowell") break
}

有时候,我们想做的不是退出整个循环,而是跳出当前的迭代,开始next一下次迭代而已:
R
repeat{
message("Happy groundhog Day")
action<-sample(
c(
"Learn French",
"Make an ice statue",
"Rob a bank",
"Win heart of Andie McDowell"
),
1
)
if(action=="Rob a bank"){
message("Quietly skipping to the next iteration")
next
}
message("action= ",action)
if(action=="Win heart of Andie McDowell") break
}
2、while循环
while循环就像是延迟了的repeat循环。它不是先执行代码再检查循环是否应该结束,而是先进行检查再执行代码。因为检查发生在开始时,所以循环体可能不会被执行。如下:
R
action<-sample(
c(
"Learn French",
"Make an ice statue",
"Rob a bank",
"Win heart of Andie McDowell"
),
1
)
while(action!="Win heart of Andie McDowell"){
message("Happy Groundhog Day!")
action<-sample(
c(
"Learn French",
"Make an ice statue",
"Rob a bank",
"Win heart of Andie McDowell"
),
1
)
message("action= ",action)
}
3、for循环
这种循环适用于已知代码所需执行的循环次数的情形。for循环将接受一个迭代器变量和一个向量参数。在每个循环中,迭代器变量会从向量中取得一个值。最简单的情况下,该向量只包含整数:
R
for(i in 1:5) message("i= ",i)

如果我们想执行多个表达式,与其他循环一样,须使用大括号把他们括起来:
R
for(i in 1:5){
j<-i^2
message("j= ",j)
}

R的for循环非常灵活,因为它们的输入并不限于整数或数字,还可以传入字符向量、逻辑向量或列表:
R
for (month in month.name){
message("The month of ",month)
}
for(yn in c(TRUE,FALSE,NA)){
message("This statement is ",yn)
}
l<-list(
pi,
LETTERS[1:5],
charToRaw("not as complicated as it looks"),
list(TRUE)
)
for (i in l){
print(i)
}
因为for循环操作于向量中的每个元素,所以它提供了一种"伪向量化"。注意,R的for循环几乎总是比其对应的向量化运行得要慢,而且往往是一到两个数量级的差别。这意味着我们应尽可能地使用向量化。