I have a common construct I've been using, and I am wondering if others do, and if there is a best practice idiom/style that people are using.
I often want to create a resulting data frame resulting from a set of operations that either produce their own slice of the output data frame, or throw an error. The way I am handling this is with the example below, where I use safely()
, then I transpose, pluck, compact, and bind rows. I use this idiom a lot, and I am wondering if others do, and if they do anything different to handle this type of work.
library(dplyr)
#> ...
library(purrr)
set.seed(123)
#;; A common idiom I use...
#;; Iterate through some values. Do this safely in case of error. Then only
#;; pick off the successful results.
1:10 %>%
map(safely(~{
if (runif(1) < 0.5) {
tibble(x = .x)
} else {
stop(paste0("Error on .x = ", .x))
}
})) %>%
transpose() %>%
pluck("result") %>%
compact() %>%
bind_rows()
#> # A tibble: 4 x 1
#> x
#> <int>
#> 1 1
#> 2 3
#> 3 6
#> 4 10
Created on 2022-06-20 by the reprex package (v2.0.1)