【问题标题】:R for loop skip to next iteration ifelseR for循环跳到下一次迭代ifelse
【发布时间】: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)}}

标签: r for-loop


【解决方案1】:
for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration
  cat(n)
}

【讨论】:

  • 整洁。致 OP:查看?Control 了解类似功能
  • 确实是非常简洁的答案,如果我想做一些类似for(n in 1:5) { if(n==3) print ('3rd iteration' ) next # skip 3rd iteration and go to next iteration cat(n) } 的事情,意思是我想打印我要跳过第三次迭代,因为在某些情况下我们需要记录我们的内容跳过以使事情易于处理。对此有什么想法吗?
  • @Jason Goal - if 语句需要额外的括号,例如 for(n in 1:5) { if(n==3) { print ('3rd iteration' ) ; next } # skip 3rd iteration and go to next iteration cat(n) }
  • 谢谢@Alexey Ferapontov,现在我明白为什么“额外括号”错误在我的旧版本中不断出现。
【解决方案2】:

如果你想跳出循环,像这样:

for(n in 1:5) { if(n==3) break # jump out of loop, not iterating cat(n) }

【讨论】:

  • 这很有趣,但没有回答问题...
  • 另外,你的评论角色位置不好(它会“评论掉”})
猜你喜欢
  • 2014-01-07
  • 1970-01-01
  • 1970-01-01
  • 2010-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-23
  • 1970-01-01
相关资源
最近更新 更多