Codementor Events

How to monitor your function progress with an elegant and simple progress bar?

Published Mar 05, 2021

Every time we do a function that contains a very large amount of loops or the repetition of intense calculations we want a way to monitor our function and to make sure that everything is going well and that there is no crash. In this sense, the most common solution is to print the index of the loop:

total <- 20
for(i in 1:total){
  print(i)
  Sys.sleep(0.2)
}

But the result can be a little uncomfortable, especially if we want to keep the results of the code in front of us on the console screen. So a more elegant solution is to use a real progress bar that can be easily printed on the console and will not hide all previous results from our screen. To do this, this code is simple:

total <- 20
# create progress bar
pb <- txtProgressBar(min = 0, max = total, style = 3)
for(i in 1:total){
  Sys.sleep(0.2)
  # update progress bar
  setTxtProgressBar(pb, i)
}
close(pb)
Discover and read more posts from Gustavo
get started
post commentsBe the first to share your opinion
Show more replies