Way to create/initialize a dplyr progress bar *not* outside of a function?

Anyone have any recommendations for how to set-up a progress bar from dplyr::progress_estimated() without explicitly creating the progress bar outside of the function?

This is the crux of what I usually do:

mydata <- tibble(x = ..., y = ..., z = ...)

progress_bar <- mydata %>%
   tally() %>%
   progress_estimated(min_time = 0)

myfunction <- function(x, y, z, ...) {

   progress_bar$tick()$print()
   function_stuff <- x + y + z
   return(function_stuff)

}

map(mydata, myfunction)

My issue is that I'd like to do this without doing the initial progress_bar <- progress_estimated(...) outside of the function. I'm trying to use a progress bar in a function that I'm adding to a package, and I feel like it wouldn't be right to assume that users will create their own progress bars each time.

Any ideas? Am I making any sense?

I think you'll manage to do that if you create the progress bar based on the input of your function.
Here is an example in {uaparsejs} :package:

ua_parse <- function(user_agents, .progress=FALSE) {

  if (.progress) pb <- progress_estimated(length(user_agents))
  purrr::map_df(user_agents, function(x) {
    if (.progress) pb$tick()$print()
    res <- .pkgenv$cache[[x]]
    if (length(res) > 0) {
      res
    } else {
      .pkgenv$cache[[x]] <- dplyr::as_data_frame(as.list(unlist(.pkgenv$ctx$call("parser.parse", x))))
      .pkgenv$cache[[x]]
    }
  })

}

See source in GH

About progress bar, you can also give a try to the {progress} :package:

3 Likes