Search code examples
rfor-loopprintingprogress

Print progress every 10 iterations for 1000 iterations


The Title says it all. I tried looking for this but to no avail.

Basically, I am running a For Loop with 1000 iterations, and I would like to write a function that shows/prints the progression of the simulation every 10 iterations.


Solution

  • How about the progress bar that is built-in with R? It prints a progress bar on the console, and let's you monitor the progress through the iterations. Unfortunately, this does not quite answer the question, because it gets updated every round of a loop, and if the number of iterations is not known beforehand, it doesn't quite get you where you want. Progress bar works as follows:

    # Number of iterations
    imax<-c(10)
    # Initiate the bar
    pb <- txtProgressBar(min = 0, max = imax, style = 3)
    # Iterations
    for(i in 1:imax) {
       Sys.sleep(1) # Put here your real simulation
       # Update the progress bar
       setTxtProgressBar(pb, i)
    }
    # Finally get a new line on the console
    cat("\n")
    

    You can certainly accomplish what you're looking after with modulus. Here's an example for the for-loop:

    for(i in 1:1000) {
       # Modulus operation
       if(i %% 10==0) {
          # Print on the screen some message
          cat(paste0("iteration: ", i, "\n"))
       }
       Sys.sleep(0.1) # Just for waiting a bit in this example
    }
    

    Would either one of these work for you?