R:如何在for循环中递增增量变量? [英] R: How to increment the incrementing variable within a for loop?

查看:337
本文介绍了R:如何在for循环中递增增量变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在满足条件时手动增加 i 变量.

I'm trying to manually increment the i variable when a condition is met.

for(i in 1:x){
   if(condition){
      i <- i + 2
      }
   }

在调试时,(i< -i + 2)行肯定在运行,但是我仍然只增加1,而不是3.(该行+2,自动增加+1)

When debugging, the (i<-i+2) line is definitely being run, but i still only increments by 1, instead of 3. (+2 from the line and an additional +1 from the auto increment)

在循环中时如何增加?

推荐答案

因此,基本上,您希望根据条件跳过一些循环迭代.这是一个理所当然的选择,但是如果必须的话,您需要next.以下代码跳过了第三,第五和第七次迭代:

So essentially you want to skip a few loop iterations based on a condition. It's a design choice that's rightfully frowned upon, but if you must, you need next. The following code skips the third, fifth and seventh iteration:

for(i in 1:10){
  if(i %in% c(3,5,7)){
    next
  }
  print(i)
}

假设您需要根据特定条件以3递增,然后可以使用一个临时变量来帮助您跳过许多步骤.请注意,这确实会在每次迭代中进行,只是会及时退出迭代:

Say you need to increment with 3 based on a certain condition, then you can use a temporary variable that helps you skip a number of steps. Note that this does go through every iteration, it just breaks out of the iteration in time:

skip <- 0 # the temporary variable helping us keeping track of the iterations
for(i in 1:10){
  if(i == 5){  # the condition that causes the skip
    skip <- 3
  }
  if(skip > 0){ # the control that skips as long as necessary
    skip <- skip - 1
    next
  }
  print(i)
}

这篇关于R:如何在for循环中递增增量变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆