1

I recently food a way to implement a progress bar in a for loop. (cf ref) An implementation could be :

size = 200
pb <- winProgressBar(title="Progress Bar", label="0% done", min=0, max=100, initial=0)
for(i in 1:size){
  Sys.sleep(0.1)

  # Progress Bar
  info <- sprintf("%d%% done", round((i/size)*100))
  setWinProgressBar(pb, i/size*100, label=info)
}
close(pb)

In order to avoid the usage of size at the beginning of the loop how can I one have a variable that would detect the total length of the iterator of the loop. So that the code would be :

pb <- winProgressBar(title="Progress Bar", label="0% done", min=0, max=100, initial=0)
for(i in 1:200){
  Sys.sleep(0.1)

  # Progress Bar
  size = ... # What to do ?
  info <- sprintf("%d%% done", round((i/size)*100))
  setWinProgressBar(pb, i/size*100, label=info)
}
close(pb)

I am aware that it will add calculus in the for loop it would just make it easy to implement in several loops without having to change their structure.

Thanks !!

Romain

Create a progress bar in R (r-bloggers)

Romain
  • 839
  • 10
  • 24
  • Why don't you know how long your vector that you loop over would be? – sgibb Nov 07 '14 at 20:22
  • Of course you know it. But let's say I have a code with 20 loops in it. I would like to copy paste the line that relates to the progress bar in the loops and avoid the struggle of having to change the parameters for every single loop. – Romain Nov 07 '14 at 20:41
  • 1
    Why you don't use `winProgressBar(..., max=size)` and in the loops `setWinProgressBar(pb, pb$getVal()+1)`? – sgibb Nov 07 '14 at 21:15
  • It works but it only transfers the problem. If I want to implement the progress on several loops I still have to manually change the parameters. I was looking for something that "dynamically" understand the size of the loop – Romain Nov 07 '14 at 21:30
  • You must know the size of a `for` loop before running it. I don't get why you can't use this information. – sgibb Nov 07 '14 at 21:32
  • Yes, you're right you must know the size. But again, my code has 100+ loops with different size. I was looking for a way to quickly copy and paste the few line of code in all the loops to have the display of the bars. I can definitely manually adapt the size variable in all the instances of winProgressBar but it would take me time, and I had the feeling something smarter was possible. – Romain Nov 07 '14 at 21:36
  • Possible duplicate of http://stackoverflow.com/questions/7349570/wrapper-to-for-loops-with-progress-bar?rq=1 – daroczig Nov 07 '14 at 22:11

0 Answers0