R for循环跳转到下一次迭代ifelse

alk*_*lki 79 for-loop r

假设你有一个像这样的for循环

for(n in 1:5) {
  #if(n=3) # skip 3rd iteration and go to next iteration
  cat(n)
}
Run Code Online (Sandbox Code Playgroud)

如果满足某个条件,如何跳到下一次迭代?

Ale*_*tov 136

for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration
  cat(n)
}
Run Code Online (Sandbox Code Playgroud)

  • 整齐.对于OP:请参阅`?Control`了解类似功能 (4认同)
  • @Jason Goal - 你需要额外的括号来表示 `if` 语句,就像这样 `for(n in 1:5) { if(n==3) { print ('3rd iteration' ) ; next } # 跳过第三次迭代并转到下一次迭代 cat(n) }` (3认同)