switch_case: Switch-style recoding of values

Description Usage Arguments Value See Also Examples

View source: R/switch_case.R

Description

Switch-style recoding of values

Usage

1
2
3
switch_case(x, ..., preserve = FALSE, default = NA)

fn_switch_case(x, fn, ..., preserve = FALSE, default = NA)

Arguments

x

A vector

...

<dynamic-dots> A sequence of two-sided formulas or named arguments.

  • Formulas: Elements of x that match the left hand side (LHS) of formulas 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.

  • Named arguments: for fn_switch_case(), named arguments are passed to the function fn. For switch_case(), named arguments will raise an error.

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.

fn

A function to apply to the left-hand side of each formula in ...

Value

A vector of the same length as x.

See Also

grep_case() to recode values with string pattern matching

fn_case(), which applies a function to both x and each formula's LHS

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

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

switch(), which inspired this function

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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
  )

data <- c(1, 4, 8, 12, 999, 6, 2, 888, 4, 6, 777)

fn_switch_case(
  data,
  function(x) paste(rep(x, 3), collapse = ""),
  7 ~ "Not asked",
  8 ~ "Refused",
  9 ~ "Missing",
  preserve = TRUE
)

incase documentation built on Jan. 16, 2021, 5:21 p.m.