3

I have a Rmarkdown document with a number of chunks. Each of them is doing a simulation inside a loop. A simulation can take anywhere from a few minutes to 20 minutes or so. I would like to keep track of when a loop is finished. However, the usual output in the Render panel does not change while a chunk is running. Currently I write some information to a text file when a loop run has finished, but that seems a bit of a hack. Is there a more elegant way to do this?

Wolfgang Rolke
  • 795
  • 4
  • 16

2 Answers2

2

Turns out there is a package dedicated to exactly this: knitrProgressBar

A minimal example usage based on the package documentation:

library(knitrProgressBar)

slow_function <- function(i, .pb=NULL) {  
  update_progress(.pb)  
  Sys.sleep(0.5)  
  i  
}

# create an R6 progress object for
# the number of loops/iterations in the target chunk

n_iterations <- 20
pb <- progress_estimated(n_iterations)
#class(pb)
#[1] "Progress" "R6"  

Executing a chunk that uses the progress object (or knitting the Rmd file), will produce progress updates for the chunk:

purrr::map_int(1:n_iterations, ~slow_function(.x, .pb = pb))

enter image description here

EDIT: closer to the question - this also works inside a loop, not just inside purrr::map

pb <- progress_estimated(n_iterations)
for(i in 1:n_iterations) {
  slow_function(i, .pb=pb)
}

enter image description here

pholzm
  • 1,719
  • 4
  • 11
0

That's just what I was looking for. Thanks

Wolfgang

Wolfgang Rolke
  • 795
  • 4
  • 16