in_case

0th

Percentile

A pipe-friendly general vectorized if

This function allows you to vectorize multiple if_else() statements. If no cases match, NA is returned. This function derived from dplyr::case_when(). Unlike dplyr::case_when(), in_case() supports piping elegantly and attempts to handle inconsistent types (see examples).

Usage
in_case(..., preserve = FALSE, default = NA)
Arguments
...

<dynamic-dots> A sequence of two-sided formulas. The left hand side (LHS) determines which values match this case. The right hand side (RHS) provides the replacement value.

The LHS must evaluate to a logical vector.

Both LHS and RHS may have the same length of either 1 or n. The value of n must be consistent across all cases. The case of n == 0 is treated as a variant of n != 1.

NULL inputs are ignored.

preserve

If TRUE, unmatched elements of the input will be returned unmodified. (The elements may have their type coerced to be compatible with replacement values.) If FALSE, unmatched elements of the input will be replaced with default. Defaults to FALSE.

default

If preserve is FALSE, a value to replace unmatched elements of the input. Defaults to NA.

Value

A vector of length 1 or n, matching the length of the logical input or output vectors. Inconsistent lengths will generate an error.

See Also

if_case(), a pipeable alternative to dplyr::if_else()

switch_case(), a reimplementation of switch()

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

Aliases
  • in_case
Examples
# NOT RUN {
# Non-piped statements are handled the same as dplyr::case_when()
x <- 1:30
in_case(
  x %% 15 == 0 ~ "fizz buzz",
  x %%  3 == 0 ~ "fizz",
  x %%  5 == 0 ~ "buzz",
  TRUE         ~ x
)

# A vector can be directly piped into in_case() without error
1:30 %>%
  in_case(
    . %% 15 == 0 ~ "fizz buzz",
    . %%  3 == 0 ~ "fizz",
    . %%  5 == 0 ~ "buzz",
    TRUE         ~ .
  )

# in_case() silently converts types
1:30 %>%
  in_case(
    . %% 15 == 0 ~ 35,
    . %%  3 == 0 ~ 5,
    . %%  5 == 0 ~ 7,
    TRUE         ~ NA
  )

x <- 1:30
try(
  dplyr::case_when(
    x %% 15 == 0 ~ 35,
    x %%  3 == 0 ~ 5,
    x %%  5 == 0 ~ 7,
    TRUE         ~ NA
  )
)

# default and preserve make it easier to handle unmatched values
1:30 %>%
  in_case(
    . %% 15 == 0 ~ "fizz buzz",
    . %%  3 == 0 ~ "fizz",
    . %%  5 == 0 ~ "buzz",
    default      = "pass"
  )

1:30 %>%
  in_case(
    . %% 15 == 0 ~ "fizz buzz",
    . %%  3 == 0 ~ "fizz",
    . %%  5 == 0 ~ "buzz",
    preserve     = TRUE
  )
# }
Documentation reproduced from package incase, version 0.1.0, License: MIT + file LICENSE

Community examples

Looks like there are no examples yet.