Switch-style recoding of values

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

parties <- sample(c("d", "r", "i", "g", "l"), 20, replace = TRUE) switch_case( parties, "d" ~ "Democrat", "r" ~ "Republican", "i" ~ "Independent", "g" ~ "Green", "l" ~ "Libertarian" )
#> [1] "Libertarian" "Green" "Libertarian" "Green" "Democrat" #> [6] "Libertarian" "Libertarian" "Libertarian" "Republican" "Independent" #> [11] "Independent" "Libertarian" "Libertarian" "Green" "Libertarian" #> [16] "Republican" "Green" "Republican" "Independent" "Democrat"
parties %>% switch_case( "d" ~ "Democrat", "r" ~ "Republican", "i" ~ "Independent", "g" ~ "Green", "l" ~ "Libertarian" )
#> [1] "Libertarian" "Green" "Libertarian" "Green" "Democrat" #> [6] "Libertarian" "Libertarian" "Libertarian" "Republican" "Independent" #> [11] "Independent" "Libertarian" "Libertarian" "Green" "Libertarian" #> [16] "Republican" "Green" "Republican" "Independent" "Democrat"
parties %>% switch_case( "d" ~ "Democrat", "r" ~ "Republican", c("i", "g", "l") ~ "Other" )
#> [1] "Other" "Other" "Other" "Other" "Democrat" #> [6] "Other" "Other" "Other" "Republican" "Other" #> [11] "Other" "Other" "Other" "Other" "Other" #> [16] "Republican" "Other" "Republican" "Other" "Democrat"
parties %>% switch_case( "d" ~ "Democrat", "r" ~ "Republican", default = "Other" )
#> [1] "Other" "Other" "Other" "Other" "Democrat" #> [6] "Other" "Other" "Other" "Republican" "Other" #> [11] "Other" "Other" "Other" "Other" "Other" #> [16] "Republican" "Other" "Republican" "Other" "Democrat"
parties %>% switch_case( "d" ~ "Democrat", "r" ~ "Republican", preserve = FALSE )
#> [1] NA NA NA NA "Democrat" #> [6] NA NA NA "Republican" NA #> [11] NA NA NA NA NA #> [16] "Republican" NA "Republican" NA "Democrat"
parties %>% switch_case( "d" ~ "Democrat", "r" ~ "Republican", preserve = TRUE )
#> [1] "l" "g" "l" "g" "Democrat" #> [6] "l" "l" "l" "Republican" "i" #> [11] "i" "l" "l" "g" "l" #> [16] "Republican" "g" "Republican" "i" "Democrat"