Case statements applying a function to all inputs
fn_case(x, fn, ..., preserve = FALSE, default = NA)
x | A vector |
---|---|
fn | A function to apply to the left-hand side of each formula in Either a quoted or unquoted function name, an anonymous The function should take two inputs, the first being |
... | <
|
preserve | If |
default | If |
A vector of length 1 or n, matching the length of the logical input or output vectors. Inconsistent lengths will generate an error.
fn_switch_case()
, which applies a function to each formula's LHS,
but not x
switch_case()
, a simpler alternative for exact matching
grep_case()
, a simpler alternative for regex pattern matching
# Replicate switch_case() parties <- sample(c("d", "r", "i", "g", "l"), 20, replace = TRUE) fn_case( parties, fn = `%in%`, "d" ~ "Democrat", "r" ~ "Republican", "i" ~ "Independent", "g" ~ "Green", "l" ~ "Libertarian" )#> [1] "Libertarian" "Green" "Libertarian" "Green" "Democrat" #> [6] "Libertarian" "Libertarian" "Libertarian" "Republican" "Independent" #> [11] "Independent" "Libertarian" "Libertarian" "Green" "Libertarian" #> [16] "Republican" "Green" "Republican" "Independent" "Democrat"# Replicate grep_case() countries <- c( "France", "Ostdeutschland", "Westdeutschland", "Nederland", "Belgie (Vlaanderen)", "Belgique (Wallonie)", "Luxembourg", "Italia" ) fn_case( countries, fn = stringi::stri_detect_regex, "Deutschland" ~ "Germany", "Belgi(qu)?e" ~ "Belgium", "Nederland" ~ "Netherlands", "Italia" ~ "Italy", preserve = TRUE, case_insensitive = TRUE )#> [1] "France" "Germany" "Germany" "Netherlands" "Belgium" #> [6] "Belgium" "Luxembourg" "Italy"# Recode values in a range time <- runif(10, 1, 12) hours <- time %/% 1 minutes <- time %% 1 * 60 hours <- hours %>% if_case(minutes > 32.5, (. + 1) %% 12, .) %>% switch_case(0 ~ 12, preserve = TRUE) %>% nombre::cardinal() minutes %>% fn_case( fn = ~ abs(.x - .y) <= 2.5, 0 ~ "o'clock", 60 ~ "o'clock", 30 ~ "half past", 15 ~ "quarter past", 45 ~ "quarter to", 5 ~ "five past", 10 ~ "ten past", 20 ~ "twenty past", 25 ~ "twenty-five past", 55 ~ "five to", 50 ~ "ten to", 40 ~ "twenty to", 35 ~ "twenty-five to" ) %>% switch_case( "o'clock" ~ paste(hours, .), default = paste(., hours) )#> [1] "twenty-five past eleven" "three o'clock" #> [3] "twenty-five past three" "half past eight" #> [5] "half past six" "five past eight" #> [7] "quarter past eight" "five past two" #> [9] "twenty-five past nine" "half past nine"