We’ve all been stuck waiting for a for loop to finish, or a particularly complex function. Over the years I have come across a few revelations when it comes to tracking the progress of my R code. Here they are in the order I found them!

  1. The print() function
for(i in 1:500){
  
	# Sleep for 0.1 seconds
	Sys.sleep(0.01)
  
	# Print progress
	print(paste("Finished", i, "of", n))
}  

print

  1. The cat() function
for(i in 1:500){
 
	# Sleep for 0.1 seconds
	Sys.sleep(0.01)

	# Print progress
	cat("Finished", i, "of", n, "\n")
}

cat

  1. The modulus operator (%%)
for(i in 1:500){
  
	# Sleep for 0.1 seconds
	Sys.sleep(0.01)

	# Print progress
	if(i %% 100 == 0){
		cat("Finished", i, "of", n, "\n")
	}
}

modulus

  1. Overwriting a printed line using \r
for(i in 1:500){
  
	# Sleep for 0.1 seconds
	Sys.sleep(0.01)

	# Print progress
	cat("\rFinished", i, "of", n)
}

overwrite

  1. My new progress() function 😊
library(basicPlotteR)

for(i in 1:500){
  
	# Sleep for 0.1 seconds
	Sys.sleep(0.01)

	# Print progress
	progress(i, n)
}

overwrite

  1. R already has one!!!! 😱
# Initialise a progress bar
pb <- txtProgressBar(min = 1, max = n, style = 3)

for(i in 1:500){
  
	# Sleep for 0.1 seconds
	Sys.sleep(0.01)

	# Print progress
	setTxtProgressBar(pb, i)
}
close(pb)

overwrite

Each of the methods of monitoring your progress are useful in different situations. Whilst the last two options look great, they are only useful inside for loops. The \r blew my mind and should work in most languages! The modulus (%%) is probably the one I use the most, allows me to check my progress without printing hundreds or thousands of lines to the screen.

Anyone who would like to use and see the code for my progress() function, you’ll find it here on github. It is part of my basicPlotteR package.