1

I've looked at a couple of questions but couldn't find a solution that doesn't use loops. I've looked here and here. Now, how could I add a progress bar that works exactly at the same time as this function:

prog<-function(){
  print("This is a test")
  Sys.sleep(05)
  setTxtProgressBar()
}

The above is a dummy function and I thought of using system.time to capture the time it takes for the print command to execute and use this for the progress bar. How could I make this work, without using a for loop? EDIT I tried this but it is still slow:

prog<-function(y=sort(runif(200)),...){
  pb<-txtProgressBar(...)
  values<-c(0,y,1)
  lapply(values, function(x){
    Sys.sleep(0.5) 
    setTxtProgressBar(pb,x)})
  Sys.sleep(1)
  close(pb)

}

Thanks.

NelsonGon
  • 13,015
  • 7
  • 27
  • 57
  • 2
    Well the problem of a progress bar is that you have to track the progress in some way, which is easy with a for loop (if each step takes about the same time). Imho prog should be low since it sets the system to sleep for 0.5 seconds and does this 202 times, if dont give another y argument. – Ben373 Feb 11 '19 at 14:29
  • Ah, changing the Sys.sleep part appears to save me some time. Thanks! – NelsonGon Feb 11 '19 at 14:30
  • 1
    have you looked at the `pbapply`-package (not sure if it can be used on your usecase though)... – Wimpel Feb 11 '19 at 14:39

1 Answers1

2

There is a package pbapply, which provides a progress bar for apply-functions using:

pblapply(X, FUN, ..., cl = NULL)

It works just like a normal apply-function.

This function: pblapply(1:10, function(x) {Sys.sleep(02); print(x)}) gave this output:

|                                                  | 0 % ~calculating  [1] 1
   |+++++                                             | 10% ~18s          [1] 2
   |++++++++++                                        | 20% ~16s          [1] 3
   |+++++++++++++++                                   | 30% ~14s          [1] 4
   |++++++++++++++++++++                              | 40% ~12s          [1] 5
   |+++++++++++++++++++++++++                         | 50% ~10s          [1] 6
   |++++++++++++++++++++++++++++++                    | 60% ~08s          [1] 7
   |+++++++++++++++++++++++++++++++++++               | 70% ~06s          [1] 8
   |++++++++++++++++++++++++++++++++++++++++         | 80% ~04s          [1] 9
   |+++++++++++++++++++++++++++++++++++++++++++++    | 90% ~02s          [1] 10
   |++++++++++++++++++++++++++++++++++++++++++++++++++| 100% elapsed = 20s

Pretty neat. I don't know if it helps, but worth taking a look.

Humpelstielzchen
  • 6,126
  • 3
  • 14
  • 34
  • I'll explore the package more. At first glance it appears to do what I did in the edit part of my question. However, I'll take more time to see how it works although honestly it's not what I intend to do but it's a start. – NelsonGon Feb 11 '19 at 16:01