View source: R/fct_case_when.R
fct_case_when | R Documentation |
Wrapper around dplyr::case_when
that converts the output to a factor and
preserves the order in which value labels were passed into the function.
fct_case_when(..., label = NULL)
... |
A sequence of two-sided formulas consistent with |
label |
A character. It's the label of the created value. |
Unlike case_when, fct_case_when allows factors to be passed in as right-hand-side arguments - they are treated internally as characters, but the resulting vector will preserve the order of the original factor levels.
The output of dplyr::case_when
, as class "factor"
and ordered
however you wanted it.
pewmethods
library(dplyr)
macrozona <- with(regiones_y_comunas,
fct_case_when(region %in% c(15, 1:4) ~ "Norte",
region %in% c(5:7, 16) ~ "Centro",
region %in% c(13) ~ "RM",
region %in% c(8:12, 14) ~ "Sur")
)
# Compare to normal case_when() and then factor(), which will arrange the levels in
# unwanted alphabetical order
macrozona <- with(regiones_y_comunas,
factor(case_when(region %in% c(15, 1:4) ~ "Norte",
region %in% c(5:7, 16) ~ "Centro",
region %in% c(13) ~ "RM",
region %in% c(8:12, 14) ~ "Sur"))
)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.