For 和 While 循环的区别
The while loop keeps executing code until its condition evaluates to FALSE.
The for loop, on the other hand, iterates over a sequence, where a looping variable changes for each iteration, according to the sequence.
while
1. 基本命令
ctr <- 1
while (ctr <= 7) {
print(paste("ctr is set to ", ctr))
ctr <- ctr + 1
}
2. break
ctr 能被 5 整除就停止循环。
ctr <- 1
while (ctr <= 7) {
if (ctr %% 5 == 0) {
break
}
print(paste("ctr is set to ", ctr))
ctr <- ctr + 1
}
for
1. 基本命令
cities <- c("New York", "Paris", "London", "Tokyo", "Rio de Janeiro", "Cape Town")
for (ci in cities) {
print(ci)
}
for (i in 1:length(cities)) {
print(cities[i])
}
条件语句有以上 2 种写法。logs
是一个列表。
如果要修改列表里面的内容,只能使用后一种方法
Using the for (log in logs)
approach here won’t work, because log
is a local copy of an element in logs. To actually access and change the elements in the logs list, you will need to use the looping index.
2. break
for (ci in cities) {
if (nchar(ci) == 6){
break
}
print(ci)
}
3. next
for (ci in cities) {
if (nchar(ci) == 6){
next
}
print(ci)
}
reference
https://campus.datacamp.com/courses/intermediate-r-practice