switch_case {incase} | R Documentation |
Switch-style recoding of values
Description
Switch-style recoding of values
Usage
switch_case(x, ..., preserve = FALSE, default = NA)
fn_switch_case(x, fn, ..., preserve = FALSE, default = NA)
Arguments
x |
A vector |
... |
<
|
preserve |
If |
default |
If |
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
switch_case_fct()
and fn_switch_case_fct()
to return a factor
and switch_case_list()
and fn_switch_case_list()
to return a list
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()
switch()
and %in%
, 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"
)
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
)