txtProgressBar, setTxtProgressBar

Create a progress bar for a loop using the txtProgressBar function, then use the setTxtProgressBar command within the loop to print the progress bar, which updates as the loop progresses.
txtProgressBar(min, max, style=1)
  • min – The minimum value in the loop.
  • max – The maximum value in the loop.
  • style – A number representing the style, where 3 is my favorite.
setTxtProgressBar(pb, value)
  • pb – A progress bar object that was output from txtProgressBar.
  • value – The current iteration value.

Example. The example below creates a loop of 100 values and uses Sys.sleep to pause for a 20ms during each loop. The progress bar is shown full, though when viewed live it progresses across the console.
> SEQ  <- seq(1,100)
> pb   <- txtProgressBar(1, 100, style=3)
> TIME <- Sys.time()
> for(i in SEQ){
+   Sys.sleep(0.02)
+   setTxtProgressBar(pb, i)
+ }
  |==========================================================| 100%
> Sys.time() - TIME
Time difference of 2.282223 secs
Tip. If each iteration in the loop is much under a millisecond, then setting the progress bar in each iteration can notably slow things down. The three blocks of code below provide another example. The loop in the first block is a "baseline" for how quickly the loop can run. The second block shows a loop that has been greatly slowed by setting the progress bar in every iteration. The final block uses an if statement with the modulo command %% to update the progress bar only once every 1000 iterations, which speeds up the code again.
> SEQ  <- seq(1,100000)
> TIME <- Sys.time()
> for(i in SEQ){
+   Sys.sleep(0.00002)
+ }
> Sys.time() - TIME
Time difference of 3.645435 secs
> 
> pb   <- txtProgressBar(1, 100000, style=3)
> TIME <- Sys.time()
> for(i in SEQ){
+   Sys.sleep(0.00002)
+   setTxtProgressBar(pb, i)
+ }
  |==========================================================| 100%
> Sys.time() - TIME
Time difference of 8.134392 secs
> 
> pb   <- txtProgressBar(1, 100000, style=3)
> TIME <- Sys.time()
> for(i in SEQ){
+   Sys.sleep(0.00002)
+   if(i %% 1000 == 0){
+     setTxtProgressBar(pb, i)
+   }
+ }
  |==========================================================| 100%
> Sys.time() - TIME
Time difference of 3.943827 secs
Thank you. Thanks to Yered Hammurabi Pita-Juarez for informing me of these great functions!

Leave a Reply