switch_branch: Perform an switch-like branch in a pipeline

Description Usage Arguments Examples

View source: R/switch_branch.R

Description

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

Usage

1
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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))

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")
  )

MyKo101/mpipe documentation built on Feb. 6, 2021, 2:13 p.m.