in_case: A pipe-friendly general vectorized if

View source: R/in_case.R

in_caseR Documentation

A pipe-friendly general vectorized if

Description

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

in_case_fct() to return a factor and in_case_list() to return a list

switch_case() a simpler alternative for when each case involves == or %in%

fn_case(), a simpler alternative for when each case uses the same function

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

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

Examples

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

incase documentation built on Aug. 21, 2023, 9:09 a.m.