tidyverse / purrr

A functional programming toolkit for R
https://purrr.tidyverse.org/
Other
1.27k stars 274 forks source link

map_case_when? #669

Closed jnolis closed 4 years ago

jnolis commented 5 years ago

Given that there is now a map with if_else functionality, would it make sense for there to exist a map_case_when?

The case_when functionality is extremely useful for avoiding nesting if_elses, so it seems like it could be useful for maps too. That seems like it could be overengineering though, I am not sure.

jennybc commented 5 years ago

Do you think you can create an example to make this more concrete and inspire discussion?

jnolis commented 5 years ago

Sure! What about the ol' trusty FizzBuzz, where I wanted to return a list that had both characters and numbers in it?

1:100 %>%
  map_case_when(
    .x %% 15 == 0 ~ "Fizzbuzz"
    .x %% 3 == 0 ~ "Fizz",
    .x %% 5 == 0 ~ "Buzz",
    TRUE ~ .x
  )
DavisVaughan commented 5 years ago

I wonder if case_when(), when powered by vctrs, should be able to take the common type of all of the 100 results of this operation and return that. In this case since it is a mix of character/integer it would just return a list

(This smells like a use case for vec_simplify())

lionel- commented 4 years ago

Thanks for the suggestion! Since case_when() is all about vectorised iteration, and map() is the opposite, it doesn't seem like a good fit.