【发布时间】:2015-11-11 15:49:20
【问题描述】:
假设你有一个这样的 for 循环
for(n in 1:5) {
#if(n=3) # skip 3rd iteration and go to next iteration
cat(n)
}
如果满足某个条件,如何跳到下一个迭代?
【问题讨论】:
-
当条件满足时不要跳过,当条件不满足时应该不跳过--
for(n in 1:5){if(n!=3){cat(n)}}
假设你有一个这样的 for 循环
for(n in 1:5) {
#if(n=3) # skip 3rd iteration and go to next iteration
cat(n)
}
如果满足某个条件,如何跳到下一个迭代?
【问题讨论】:
for(n in 1:5){if(n!=3){cat(n)}}
for(n in 1:5) {
if(n==3) next # skip 3rd iteration and go to next iteration
cat(n)
}
【讨论】:
?Control 了解类似功能
for(n in 1:5) { if(n==3) print ('3rd iteration' ) next # skip 3rd iteration and go to next iteration cat(n) } 的事情,意思是我想打印我要跳过第三次迭代,因为在某些情况下我们需要记录我们的内容跳过以使事情易于处理。对此有什么想法吗?
if 语句需要额外的括号,例如 for(n in 1:5) { if(n==3) { print ('3rd iteration' ) ; next } # skip 3rd iteration and go to next iteration cat(n) }
如果你想跳出循环,像这样:
for(n in 1:5) { if(n==3) break # jump out of loop, not iterating cat(n) }
【讨论】:
})