richpiana
richpiana

Reputation: 421

R progress bar based on number of seconds given

I am creating a function to be used by different user. Since the function is long I would like to create a progress bar based on the number of second (estimated by me) in order to bring confidence to the user that the code is working. My proposal (based on an answer found on stakoverflow). The problem is that I do not know how to convert this '200000' into seconds. Any help?

library(progress)


  total <- 200000
  # create progress bar
  pb <- txtProgressBar(min = 0, max = total, style = 3)
  for(i in 1:total){
    # update progress bar
    setTxtProgressBar(pb, i)
  }
  close(pb)

Upvotes: 1

Views: 266

Answers (2)

MSR
MSR

Reputation: 2891

Here's another option, using Sys.sleep. This will go for 7 seconds.

library(progress)

secs <- 7
pb <- progress_bar$new(total = secs)
for (i in 1:secs) {
  pb$tick()
  Sys.sleep(1)
}

Set secs as required.

Upvotes: 1

Dominic Comtois
Dominic Comtois

Reputation: 10411

Something like this maybe? If you want the bar to be updated only once per second, simply remove the *2 (two places) and replace .5 with 1 in Sys.sleep().

start_pb <- function(secs) {
  # create progress bar
  pb <- txtProgressBar(min = 0, max = secs*2, style = 3)
  for(i in 1:(secs*2)) {
    # update progress bar
    Sys.sleep(.5)
    setTxtProgressBar(pb, i)
  }
  close(pb)
}

start_pb(20)

Upvotes: 0

Related Questions