Style/idiom question on common dplyr/purrr operations

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)

This does much the same with fewer steps. Will it work for you?

library(tidyverse)
#> Warning: package 'tibble' was built under R version 4.1.2
set.seed(123)
1:10 %>%
  map_dfr(safely(~{
    if (runif(1) < 0.5) {
      .x
    } else {
      NULL
    }
  }))
#> # A tibble: 4 x 1
#>   result
#>    <int>
#> 1      1
#> 2      3
#> 3      6
#> 4     10

Created on 2022-06-20 by the reprex package (v2.0.1)

1 Like

Thanks FJCC, this does work in your case here. However, it won't necessarily work in my case because the stop()/error throw is what is actually happening, and I have do deal with that.

Here's another option

1:10 %>%
  map_dfr(possibly(~{
    if (runif(1) < 0.5) {
      tibble(x = .x)
    } else {
      stop(paste0("Error on .x = ", .x))
    }
  },otherwise = tibble(x=numeric(0))))
1 Like

HI @ nirgrahamuk , this looks like the idiom I am probably looking for, thank you!