【问题标题】:R, how to increment the a for loop limit within the loop itself?R,如何在循环本身内增加 a for 循环限制?
【发布时间】:2020-02-04 19:17:04
【问题描述】:

我在 R 中工作,我正在尝试更改循环本身内 for 循环的限制,但我无法成功。

这是我的玩具代码:

setwd(".")
options(stringsAsFactors = FALSE)
cat("\014")
set.seed(11)


execution_limit <- 10

for(exe_i in 1:execution_limit)
{
    cat("(exe_i = ", exe_i," / ", execution_limit,  ")\n", sep="")
    Sys.sleep(0.1)

    if(exe_i == 7) {
            execution_limit <- 15
    }
}

打印输出:

(exe_i = 1 / 10)
(exe_i = 2 / 10)
(exe_i = 3 / 10)
(exe_i = 4 / 10)
(exe_i = 5 / 10)
(exe_i = 6 / 10)
(exe_i = 7 / 10)
(exe_i = 8 / 15)
(exe_i = 9 / 15)
(exe_i = 10 / 15)

循环在 10 次迭代后停止,但我想继续到第 15 次迭代。 我该怎么做?

谢谢

【问题讨论】:

  • 如果迭代次数不固定,您可以使用whilerepeat 循环代替for 循环。
  • 感谢您的评论。如何使用while?你能举个例子吗?

标签: r loops for-loop


【解决方案1】:

您可以像这样使用while 循环(请注意,您必须自己增加exe_i

execution_limit <- 10
exe_i <- 1
while(exe_i <= execution_limit)
{
    cat("(exe_i = ", exe_i," / ", execution_limit,  ")\n", sep="")
    Sys.sleep(0.1)

    if(exe_i == 7) {
            execution_limit <- 15
    }
    exe_i <- exe_i + 1
}

# (exe_i = 1 / 10)
# (exe_i = 2 / 10)
# (exe_i = 3 / 10)
# (exe_i = 4 / 10)
# (exe_i = 5 / 10)
# (exe_i = 6 / 10)
# (exe_i = 7 / 10)
# (exe_i = 8 / 15)
# (exe_i = 9 / 15)
# (exe_i = 10 / 15)
# (exe_i = 11 / 15)
# (exe_i = 12 / 15)
# (exe_i = 13 / 15)
# (exe_i = 14 / 15)
# (exe_i = 15 / 15)

【讨论】:

    猜你喜欢
    • 2014-12-12
    • 2019-01-17
    • 2021-10-28
    • 2017-01-26
    • 2022-01-01
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多