Interesting tidy eval use cases

I think your function feels so complex because you're attacking the problem at the slightly wrong level. I think it's easier if you think about writing a vectorised function that you can use in concert with mutate():

library(tidyverse)

df <- tibble(
  a = c("b", "d", "l", "m"), 
  x = c(NA, NA, 1, 3), 
  y = c(2, NA, 2, 3), 
  z = c(1, 2, 0, NA)
)

first_match <- function(.f, ...) {
  tibble(...) %>% 
    transpose() %>% 
    map_dbl(~ purrr::detect(.x, .f) %||% NA)
}

df %>% mutate(new_col = first_match(~ . > 1, x, y, z))  
#> # A tibble: 4 x 5
#>   a         x     y     z new_col
#>   <chr> <dbl> <dbl> <dbl>   <dbl>
#> 1 b        NA     2     1       2
#> 2 d        NA    NA     2       2
#> 3 l         1     2     0       2
#> 4 m         3     3    NA       3

We're planning on thinking about ways for first_match() to have selection semantics so you could simplify further to first_match(~ . > 1, x:y)

1 Like