【问题标题】:Varying the number of iterations in a for loop depending on results in the body of the for loop in R根据 R 中 for 循环体的结果改变 for 循环中的迭代次数
【发布时间】:2020-05-09 11:41:46
【问题描述】:

这是我尝试在 for 循环中改变迭代的代码

repscount <- value
for (i in 1:repscount) { 
  ##certain calculations on x
  if (x == 0) {repscount <- repscount + 1} else{}##add x to a list
}

但我的代表人数没有增加。是否重写了 repscount 的值?有没有不使用while循环的另一种方法?

【问题讨论】:

  • 很可能是因为x 不完全是0

标签: r for-loop iteration


【解决方案1】:

您的代码不起作用,因为for 首先检查它必须执行多少次运行。更改repscount 后,for 函数将不再检查它应该执行的迭代次数。这个简单的例子说明:

n <- 5
for (i in 1:n) {
  print(i)
  n <- n + 1
}

所以首先for 内部的条件是评估。 R 知道它会进行五次迭代并这样做。 n 之后发生变化的事实对此没有影响。

您可以改用while 循环:

repscount <- value
i <- 1
while (i <= repscount) { 
  ##certain calculations on x
  if (x == 0) {repscount <- repscount + 1} else {}##add x to a list
  i <- i + 1     
}

这里,在每次运行结束后,repscounti 进行比较,只有在 i &lt;= repscount 时才会从头开始迭代。

【讨论】:

  • 是的,我知道这行得通。但这大大减慢了我的代码。没有别的办法吗?
  • 当然还有其他方法,但恐怕没有for loops。此外,如果这会减慢代码的速度,那么等效的 for 循环也会减慢代码的速度。通常,为了提高性能,您会希望尽可能避免循环。此外,如果正文中的列表很大,那么向该列表中添加内容也可能非常慢。
猜你喜欢
  • 1970-01-01
  • 2012-08-07
  • 2016-02-16
  • 1970-01-01
  • 2021-12-20
  • 1970-01-01
  • 2012-10-27
  • 2014-08-24
  • 1970-01-01
相关资源
最近更新 更多