incase (version 0.1.0)

if_case: Pipe-friendly vectorized if

Description

Compared to dplyr::if_else(), this function is easier to use with a pipe. A vector piped into this function will be quietly ignored. This allows magrittr dots to be used in arguments without requiring workarounds like wrapping the function in braces.

Usage

if_case(condition, true, false, missing = NA, ...)

Arguments

condition

Logical vector

true, false, missing

Values to use for TRUE, FALSE, and NA values of condition. They must be either the same length as condition, or length 1.

...

Values passed to ... produce an error. This facilitates the quiet ignoring of a piped vector.

Value

Where condition is TRUE, the matching value from true; where it's FALSE, the matching value from false; and where it's NA, the matching value from missing.

Details

This function is also less strict than dplyr::if_else(). If true, false, and missing are different types, they are silently coerced to a common type.

See Also

in_case(), a pipeable alternative to dplyr::case_when()

switch_case(), a reimplementation of switch()

dplyr::if_else(), from which this function is derived

Examples

Run this code
# NOT RUN {
x <- c(1, 2, 5, NA)

# if_case() produces the same output as dplyr::if_else()
if_case(x > 3, "high", "low", "missing")
dplyr::if_else(x > 3, "high", "low", "missing")

# if_case() does not throw an error if arguments are not of the same type
if_case(x > 3, "high", "low", NA)
try(dplyr::if_else(x > 3, "high", "low", NA))

# if_case() can accept a piped input without an error or requiring braces
x %>% if_case(. > 3, "high", "low", "missing")
try(x %>% dplyr::if_else(. > 3, "high", "low", "missing"))
x %>% {dplyr::if_else(. > 3, "high", "low", "missing")}

# You can also pipe a conditional test like dplyr::if_else()
{x > 3} %>% if_case("high", "low", "missing")
{x > 3} %>% dplyr::if_else("high", "low", "missing")
# }

Run the code above in your browser using DataCamp Workspace