in_case {incase} | R 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
... |
< The LHS must evaluate to a logical vector. Both LHS and RHS may have the same length of either 1 or
|
preserve |
If |
default |
If |
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
)