purrr icon indicating copy to clipboard operation
purrr copied to clipboard

pmap_dfr safe

Open q-w-a opened this issue 2 years ago • 0 comments

Idea for a feature related to pmap_dfr:

It may be useful to implement a version of pmap_dfr that has will not crash upon receiving an input that throws an error, but instead warns the user about which entries are dropped to ensure they understand what data is being lost. This is simple to do with functionality from purrr's possibly function, but having a single function that does this could be quite convenient. Would you consider a pull request on this topic?

library(purrr)

# continue if function f throws an error and message user about which entries failed
pmap_dfr_safe <- function(l, f, quiet = TRUE, ..., .id = NULL) {
  f <- purrr::possibly(f, otherwise = NULL, quiet)
  res <- purrr::pmap(l, f, ...)
  passed <- purrr::map_lgl(res, ~!is.null(.x)) 
  failed <- which(!passed)

  if (length(failed) > 0) {
    message("The entries at the following indices will be dropped: ")
    message(failed)
  }
  
  dplyr::bind_rows(res[passed], .id = .id)
}


params <- list(max = list(10, 20, 30),
       min = list(5, 10, 15),
      p = list(.25, "X", .75))



result <- pmap_dfr_safe(params, ~data.frame(x = qunif(...), y = qunif(...)))
#> The entries at the following indices will be dropped:
#> 2


head(result)
#>       x     y
#> 1  6.25  6.25
#> 2 26.25 26.25

q-w-a avatar Feb 25 '22 03:02 q-w-a