A simple progress-bar in R

A progress-bar is quite useful for displaying the current state of an iterating process, such as in a loop called using the for function in R.

Below you can see my very quick and easy to use function for employing the progress-bar feature in R. Here is the code:

# An easy progress bar all-in-one function

ProgressBar <- function(x = NA) {
  StartProgress <- function(x) {
    width <- getOption("width")
    width <- if (100 > (width - 10)) width - 10 else 100
    .progressbar <<- txtProgressBar(min=0, max=x, style=3, width=width)
    .progressmax <<- x
    .progressint <<- 0
  CloseProgress <- function() {
    if (exists(".progressbar", envir=.GlobalEnv)) {
      rm(list=c(".progressbar", ".progressmax", ".progressint"),
  if (is.null(x)) {
  } else {
    if (!is.na(x)) {
    } else {
      if (exists(".progressbar", envir=.GlobalEnv)) {
        .progressint <<- .progressint + 1
        if (.progressint <= .progressmax)
          setTxtProgressBar(.progressbar, .progressint)
        if (.progressint == .progressmax)

To use the code, one simply has to tell the function how many iterations of a loop are coming; this is the only parameter. The total number of iterations, of course, has to be known. Otherwise the function does not know when 100% is reached. Then, the function has to be called within a loop, but without any parameter. After the loop, the progress-bar function is called again, with “NULL” as parameter value, to end the display of the progress-bar; but this is optional.

Below is an example of how to use the ProgressBar function:

# define how many iterations will be performed in the loop
x <- 666

# start by giving the total number of iterations

# call function within a loop
for (i in 1:x) {

# end the progress bar (optional)

The resulting output is displayed in the R console, and looks like this (when completed):

|===============================================================| 100%

I used this function in many applications, or just to see how long some runs are going to take while testing a new code. I hope you enjoy it.

1 reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply to Alex Bunten Cancel reply