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?
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))
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)
}