Allows the user to perform an if/else-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 fun and elsefun, however any function can be used.

if_branch(data, predicate, fun, elsefun = NULL)

Arguments

data

the data being passed through the pipeline

predicate

logical statement, a function or an expression that can be evaluated in the context of data to decide which branch to follow

fun

pipeline to follow if predicate evaluates as TRUE

elsefun

pipeline to follow if predicate evaluates as FALSE, or NULL if nothing is to happen to the original data.

Examples

1 %>% magrittr::multiply_by(2) %>% if_branch( . %>% magrittr::equals(2), . %>% magrittr::multiply_by(3) %>% magrittr::add(2) ) %>% magrittr::multiply_by(2)
#> [1] 16
tibble::tibble(x = rnorm(100), y = rnorm(100)) %>% dplyr::mutate(z = x + y) %>% if_branch( mean(z) > 0, . %>% pipe_cat("z is high\n\n"), . %>% dplyr::select(-z) %>% pipe_cat("z is low, so it was dropped\n\n") )
#> z is high #>
#> # A tibble: 100 x 3 #> x y z #> <dbl> <dbl> <dbl> #> 1 -0.554 -0.209 -0.763 #> 2 0.629 -1.40 -0.770 #> 3 2.07 0.259 2.32 #> 4 -1.63 -0.442 -2.07 #> 5 0.512 0.569 1.08 #> 6 -1.86 2.13 0.264 #> 7 -0.522 0.425 -0.0972 #> 8 -0.0526 -1.68 -1.74 #> 9 0.543 0.249 0.792 #> 10 -0.914 1.07 0.159 #> # … with 90 more rows