incase (version 0.1.0)

switch_case: Switch-style recoding of values

Description

Switch-style recoding of values

Usage

switch_case(x, ..., preserve = FALSE, default = NA)

Arguments

x

A vector

...

<dynamic-dots> A sequence of two-sided formulas. Elements of x that match the left hand side (LHS) will be replaced with the value in the right hand side (RHS).

The LHS must evaluate to an atomic vector.

The RHS must be of length one.

NULL inputs are ignored.

preserve

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

default

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

Value

A vector of the same length as x.

See Also

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

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

switch(), which inspired this function

Examples

Run this code
# NOT RUN {
parties <- sample(c("d", "r", "i", "g", "l"), 20, replace = TRUE)

switch_case(
  parties,
  "d" ~ "Democrat",
  "r" ~ "Republican",
  "i" ~ "Independent",
  "g" ~ "Green",
  "l" ~ "Libertarian"
)

parties %>%
  switch_case(
    "d" ~ "Democrat",
    "r" ~ "Republican",
    "i" ~ "Independent",
    "g" ~ "Green",
    "l" ~ "Libertarian"
  )

parties %>%
  switch_case(
    "d" ~ "Democrat",
    "r" ~ "Republican",
    c("i", "g", "l") ~ "Other"
  )

parties %>%
  switch_case(
    "d" ~ "Democrat",
    "r" ~ "Republican",
    default = "Other"
  )

parties %>%
  switch_case(
    "d" ~ "Democrat",
    "r" ~ "Republican",
    preserve = FALSE
  )

parties %>%
  switch_case(
    "d" ~ "Democrat",
    "r" ~ "Republican",
    preserve = TRUE
  )
# }

Run the code above in your browser using DataLab