R: Text progress bar in for loop

for progress bar to work you need a number to track your progress. that is one of the reasons as a general rule I prefer using for with (i in 1:length(ind)) instead of directly putting the object I want there. Alternatively you'll just create another stepi variable that you do stepi = stepi + 1 in every iteration.

you first need to create the progressbar object outside the loop

pb = txtProgressBar(min = 0, max = length(ind), initial = 0) 

then inside you need to update with every iteration

setTxtProgressBar(pb,stepi)

or

setTxtProgressBar(pb,i)

Remember to close the progress bar to output the newline character. From the documentation:

The progress bar should be closed when finished with: this outputs the final newline character.

Simply add at the end of your loop:

close(pb)

This will work poorly if the loop also has print commands in it


You could write a very simple one on the fly to show percent completed:

n <- 100
for (ii in 1:n) {
  cat(paste0(round(ii / n * 100), '% completed'))
  Sys.sleep(.05)
  if (ii == n) cat(': Done')
  else cat('\014')
}
# 50% completed

Or one to replicate the text bar:

n <- 100
for (ii in 1:n) {
  width <- options()$width
  cat(paste0(rep('=', ii / n * width), collapse = ''))
  Sys.sleep(.05)
  if (ii == n) cat('\014Done')
  else cat('\014')
}
# ============================

Another one with text bar and percent complete:

options(width = 80)
n <- 100
for (ii in 1:n) {
  extra <- nchar('||100%')
  width <- options()$width
  step <- round(ii / n * (width - extra))
  text <- sprintf('|%s%s|% 3s%%', strrep('=', step),
                  strrep(' ', width - step - extra), round(ii / n * 100))
  cat(text)
  Sys.sleep(0.05)
  cat(if (ii == n) '\n' else '\014')
}

|==================================================                        | 67%

Now there is an easier solution by package svMisc, simply put progress() in your for loop, for example

library(svMisc)
for (i in 1:n){
# <YOUR CODES HERE>
progress(i)
}