Search code examples
rdictionarycommand-line-interfaceprogress-barpurrr

R cli progress bar within purrr::map


I need to present a progress bar that show the progress of a purrr::pmap. I use the cli package for user facing information generally, and there is a progress bar in there that seems proficient. However, I cannot get access to a created progress bar inside of another function.

library(cli)
library(purrr)

a <- 1:1000
p <- cli::cli_progress_bar(total = length(a))
te <- function(x){
  cli::cli_progress_update(id=p)
  return(1/x)
}

cli_progress_done(id=p)

a |> purrr::map(te)

It seems that the id argument is not used? Is there a way to access the progress bar inside of the inner function so that I can update the progress?

Thanks!

Fredrik


Solution

  • You could use the .progress argument (its based on cli) in purrr::map():

    a <- 1:1000
    map(a, function(x){Sys.sleep(1/100); (1/x)}, .progress = list(
      type = "iterator", 
      format = "Calculating {cli::pb_bar} {cli::pb_percent}",
      clear = TRUE))
    

    enter image description here