1

Say I have the following R script, where cat provides the user with some feedback on what is being done and Sys.sleep stands for the actual computations being carried on:

cat("Doing something\n")
Sys.sleep(1)
cat("Doing something else\n")
Sys.sleep(1)
cat("Finalizing\n")
setTxtProgressBar(pb, 3/3)

I would like to insert a progress bar on those cat calls (pun not intended) so the user has an idea of how far into the script they are. This is what I could come up so far:

pb <- txtProgressBar(style = 3)
cat("\nDoing something\n")
Sys.sleep(1)
setTxtProgressBar(pb, 1/3)
cat("\nDoing something else\n")
Sys.sleep(1)
setTxtProgressBar(pb, 2/3)
cat("\nFinalizing\n")
setTxtProgressBar(pb, 3/3)

The problem with this is that I have to manually set the progress bar updates (1/3, 2/3, 3/3), which is annoying and cumbersome, especially on longer scripts. My idea is to set those fractions as currentScriptLine/totalScriptLines, but I have no idea how to set these parameters. From what I've researched, R doesn't have a function to return the current or total number of lines from the script it is currently running. Or is there? How else could I tackle this problem of giving the user feedback on how far he is on the script?

Waldir Leoncio
  • 10,853
  • 19
  • 77
  • 107
  • 1
    Maybe another idea: If you know the number of calls in advance, you could `pb <- create_progress_bar("text"); pb$init(n)` and then `pb$step()`. – lukeA Apr 22 '15 at 20:36

0 Answers0