bkitej
bkitej

Reputation: 96

R: Progress bar does not start at 0

I've attempted to write a progress bar with R's "progress" library. In all efforts made, the bar starts at over ten percent.

I'm using the exact example code (https://github.com/r-lib/progress#readme), and have the current version of the package (1.2.0). I'm running this code in the Anaconda distribution of RStudio, version 1.0.153.

library(progress)
pb <- progress_bar$new(total = 100)
for (i in 1:100) {
  pb$tick()
  Sys.sleep(1 / 100)
}

The progress bar should begins at 0, but instead begins at 20%. It does complete correctly at 100%.

Upvotes: 0

Views: 510

Answers (1)

Lisa DeBruine
Lisa DeBruine

Reputation: 878

TL;DR: Add pb$tick(len=0); Sys.sleep(0.5); pb$tick(len=0) right after you make the progress bar. You might need to adjust the sleep time. This is unsatisfyingly hacky but works.


This illustrates the problem a little better:

f <- function(wait = 1, total = 5) {
  pb <- progress::progress_bar$new(total = total)
  pb$tick(len = 0) # doesn't seem to work

  for (i in 1:total) {
    print(i)
    pb$tick(len = 1)
    Sys.sleep(wait)
  }
}

If I run f(1) I get:

[1] 1
[1] 2
[=============>----------------------]  40%[1] 3
[=====================>--------------]  60%[1] 4
[============================>-------]  80%[1] 5

But if I run f(1/10) I get:

[1] 1
[1] 2
[1] 3
[=====================>--------------]  60%[1] 4
[============================>-------]  80%[1] 5

And f(1/100) results in:

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

So there must be some sort of startup time for the progress bar. On my computer it's about 140 ms (try f(1/1000, 200)). But even if I set wait to something long (like f(5)) I still don't get a first display.


If I add a pre-wait time after pb$tick(len = 0) (not before), then I get a first tick (as long as the pre-wait time is ~> 200 ms):

f <- function(wait = 1, total = 5, pre = 1) {
  pb <- progress::progress_bar$new(total = total)
  pb$tick(len = 0) # doesn't display
  Sys.sleep(pre)   # pre-waiting time
  pb$tick(len=0)   # now it displays the 0% bar
  
  for (i in 1:total) {
    print(i)
    pb$tick()
    Sys.sleep(wait)
  }
}
> f(1/100, 5, 0.3)
[======>---------------------------]   0%[1] 1
[======>---------------------------]  20%[1] 2
[=============>--------------------]  40%[1] 3
[===================>--------------]  60%[1] 4
[==========================>-------]  80%[1] 5

Upvotes: 1

Related Questions