Allows the user to perform a switch-like branch without breaking out of a pipeline. To maintain the flow of a pipeline, it is recommended to use fseq style arguments (i.e. pipelines) for the cases, however any function can be used. If no cases match, then the original data is passed unchanged

switch_branch(data, case, ..., warn = F)

Arguments

data

the data being passed through the pipeline.

case

an expression to be evaluated in the context of data to decide which branch to follow. Must evaluate to numeric or a character string.

...

the list of alternatives. If case is numeric, then the case-th alternative will be chosen (if it exists), if case is a character, then it will be compared against the names of one of these alternatives. If no character matches are found (or the numeric is out of range), then the data will be returned untouched.

warn

whether or not to warn that no cases were chosen

Examples

tibble::tibble( x = rnorm(10), y = sample(c("red", "blue", "yellow"), 10, replace = TRUE ) ) %>% dplyr::arrange(x) %>% switch_branch(. %>% dplyr::slice(1) %>% dplyr::pull(y), red = . %>% pipe_cat("top was red\n") %>% dplyr::filter(y == "red"), blue = . %>% pipe_cat("top was blue\n") %>% dplyr::filter(x < 0) ) %>% dplyr::summarise(m.x = mean(x))
#> top was blue
#> # A tibble: 1 x 1 #> m.x #> <dbl> #> 1 -1.06
palmerpenguins::penguins %>% dplyr::mutate(species = factor(species, levels = c("Gentoo", "Adelie", "Chinstrap"))) %>% dplyr::sample_n(1) %>% switch_branch( . %>% dplyr::pull(species) %>% as.numeric(), . %>% pipe_cat("Selected row is Gentoo\n"), . %>% pipe_cat("Selected row is Adelie\n"), . %>% pipe_cat("Selected row is Chinstrap\n") )
#> Selected row is Gentoo
#> # A tibble: 1 x 8 #> species island bill_length_mm bill_depth_mm flipper_length_… body_mass_g sex #> <fct> <fct> <dbl> <dbl> <int> <int> <fct> #> 1 Gentoo Biscoe 40.9 13.7 214 4650 fema… #> # … with 1 more variable: year <int>