Update: Apparently this feature is now planned for dplyr, as discussed here: https://github.com/tidyverse/dplyr/pull/6145
In SQL one can assign multiple variables - say var1 and var2 - when a given case is verified, with a construction like
case when condition then var1 = x, var2 = y
Does dplyr::case_when (or anything else in the tidyverse) support this useful feature), and if so, how?!
Note that in the example below, var1, var2 and var3 have exactly the same test conditions, i.e. Species == "setosa", and the degenerate case TRUE. I want to reduce this redundancy by not repeating the conditions: one call to case_when (or similar), albeit with different eval_on_true expressions for var1, var2 and var3, respectively. Obviously redundancy is not a problem here in this example, but my case_when's get very large and complex in real life examples.
library(tidyverse)
# create example data
set.seed(1337)
data <- iris %>%
sample_n(5) %>%
select(Petal.Length, Petal.Width, Species) %>%
as_tibble()
data
#> # A tibble: 5 × 3
#> Petal.Length Petal.Width Species
#> <dbl> <dbl> <fct>
#> 1 5.5 1.8 virginica
#> 2 5 1.9 virginica
#> 3 1.5 0.2 setosa
#> 4 5.9 2.3 virginica
#> 5 4.1 1.3 versicolor
data %>%
mutate(var1 = case_when(Species == "setosa" ~ "green", TRUE ~ "blue"),
var2 = case_when(Species == "setosa" ~ Petal.Length * 99, TRUE ~ Petal.Length),
var3 = case_when(Species == "setosa" ~ as.Date("2002-12-01"), TRUE ~ as.Date("2003-12-02")))
#> # A tibble: 5 × 6
#> Petal.Length Petal.Width Species var1 var2 var3
#> <dbl> <dbl> <fct> <chr> <dbl> <date>
#> 1 5.5 1.8 virginica blue 5.5 2003-12-02
#> 2 5 1.9 virginica blue 5 2003-12-02
#> 3 1.5 0.2 setosa green 148. 2002-12-01
#> 4 5.9 2.3 virginica blue 5.9 2003-12-02
#> 5 4.1 1.3 versicolor blue 4.1 2003-12-02
Created on 2022-02-09 by the reprex package (v2.0.1)