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.

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

x <- c(1, 2, 5, NA)

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

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

# if_case() can accept a piped input without an error or requiring braces
x %>% if_case(. > 3, "high", "low", "missing")
#> [1] "low"     "low"     "high"    "missing"
try(x %>% dplyr::if_else(. > 3, "high", "low", "missing"))
#> Error in dplyr::if_else(., . > 3, "high", "low", "missing") : 
#>   `...` must be empty.
#>  Problematic argument:
#>  ..1 = "missing"
#>  Did you forget to name an argument?
x %>% {dplyr::if_else(. > 3, "high", "low", "missing")}
#> [1] "low"     "low"     "high"    "missing"

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