Created
October 24, 2021 15:13
-
-
Save IndrajeetPatil/baff8cf625d9fcd5ef2a36f520373426 to your computer and use it in GitHub Desktop.
Alternative to `case_when` when multiple conditions present
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(dplyr, warn.conflicts = FALSE) | |
l <- letters[1:3] | |
n <- 1:3 | |
df <- tibble(x = c(rep(l, 2), "x")) | |
# thanks to Bret Beheim | |
df %>% mutate(y = n[match(x, l)]) | |
# thanks to Lisa DeBruine and Brenton Wiernik | |
df %>% mutate(y = recode(!!!setNames(n, l), x, .default = NA_integer_)) | |
# thanks to Mickaël Canouil | |
f <- function(.x) if (length(out <- n[l %in% .x]) == 0) NA_integer_ else out | |
df %>% rowwise() %>% mutate(y = f(x)) %>% ungroup() # option-1 | |
df %>% mutate(y = purrr::map_int(x, f)) # option-2 | |
# thanks to Henrik Singmann | |
names(n) <- l | |
df %>% mutate(y = n[x]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Context:
https://twitter.com/patilindrajeets/status/1452199333827334150?s=20
Reprex:
Created on 2021-10-24 by the reprex package (v2.0.1)
Session info