Progress bars and for loops.

Today somebody asked me about building a progress bar into a for loop. This can be really useful if you are running lots of bootstrapping or Monte Carlo simulations, and you want some peace of mind so that you know that loop is still running as the computer chugs away in the background. It’s good to know whether it’s worth hanging around for the code finish, or better to go climbing/ skiing for the weekend/ or whether there is just time for a cup of tea.

I’ve written a dummy script here to show how this can be done. Fortunately the built in R.utils package contains a function for incorporating a progress bar on the R console using the function txtProgressBar(). I thought it would be fun for the for loop to actually do something, so I made it write out a message (stored in the cdRclb object) in an empty plot window. Here is the script:

# Write a message to plot and make an empty plot window
cdRclb  <-c( "c","o","d", "e", "R", "c", "l", "u", "b")
plot(x= 1:9, y = 1:9, type="n", axes=FALSE, frame.plot = TRUE, ann=FALSE)

So that the progress bar takes at least some time to finish, I decided to run the for loop for 900000 iterations (100000 x the length() of the object cdRclb).

# Set the number of iterations for the loop
nIts <- length(cdRclb) *100000

Then make the progress bar and write the loop. You write the txtProgressBar() function first, outside of the loop, and everything within the {} is repeated for nIts, the number of iterations. Here, for each iteration we find a new value, k, the iteration number in the loop divided by 100000.

Still within the for loop, we use an if statement to decide whether we should write-out out some of the message stored in cdRclb. When k is a round number, we write an item of cdRclb using text(). At the end of the iteration we update the progress bar using setTxtProgressBar() and the loop starts over. Check what happens in the plot window as the loop progresses, and also check the R console. Fun and extremely satisfying!

# create the progress bar
progBar <- txtProgressBar(min = 0, max = nIts, style = 3)

# Start the for loop.
for(i in 1:nIts){
	# Find k. NB, lots of other functions/commands could go here.
	k <- i/100000 
	# Use an if command to decide whether to plot part of the message. Only this when k is a whole number
	if(floor(k)==k) text(x = k ,y = 5, labels = cdRclb[k],  col= k+1, cex = 4)
   	# Update the progress bar
   	setTxtProgressBar(progBar, i)

# Close the progress bar

Leave a Reply

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.