0

I am working in R and I am trying to change the limit of a for loop within the loop itself, but I cannot succeed.

Here's my toy peace of code:

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
    }
}

Printed output:

(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)

The loop stops after 10 iterations, but I would like to go on until the 15th iteration. How can I do that?

Thanks

DavideChicco.it
  • 3,318
  • 13
  • 56
  • 84

1 Answers1

1

You could use a while loop like this (note that you must increment exe_i yourself)

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)
IceCreamToucan
  • 28,083
  • 2
  • 22
  • 38