Turn case_when output into an ordered factor

case_when_factor(...)

Arguments

...

<dynamic-dots> A sequence of two-sided formulas. The left hand side (LHS) determines which values match this case. The right hand side (RHS) provides the replacement value.

The LHS must evaluate to a logical vector. The RHS does not need to be logical, but all RHSs must evaluate to the same type of vector.

Both LHS and RHS may have the same length of either 1 or n. The value of n must be consistent across all cases. The case of n == 0 is treated as a variant of n != 1.

NULL inputs are ignored.

Value

An ordered factor vector of length 1 or n, matching the length of the logical input or output vectors, with the type (and attributes) of the first RHS. Inconsistent lengths or types will generate an error.

References

https://stackoverflow.com/questions/49572416/r-convert-to-factor-with-order-of-levels-same-with-case-when

Examples

#> #> Attaching package: ‘dplyr’
#> The following objects are masked from ‘package:stats’: #> #> filter, lag
#> The following objects are masked from ‘package:base’: #> #> intersect, setdiff, setequal, union
mtcars2 <- mtcars %>% mutate( mpg_bin = case_when( mpg < 10 ~ "mpg < 10", mpg >= 10 & mpg < 20 ~ "10 <= mpg < 20", TRUE ~ "20 <= mpg" ), mpg_bin_factor = case_when_factor( mpg < 10 ~ "mpg < 10", mpg >= 10 & mpg < 20 ~ "10 <= mpg < 20", TRUE ~ "20 <= mpg" ) ) %>% select(mpg, starts_with("mpg_bin")) %>% as_tibble() mtcars2
#> # A tibble: 32 x 3 #> mpg mpg_bin mpg_bin_factor #> <dbl> <chr> <fct> #> 1 21 20 <= mpg 20 <= mpg #> 2 21 20 <= mpg 20 <= mpg #> 3 22.8 20 <= mpg 20 <= mpg #> 4 21.4 20 <= mpg 20 <= mpg #> 5 18.7 10 <= mpg < 20 10 <= mpg < 20 #> 6 18.1 10 <= mpg < 20 10 <= mpg < 20 #> 7 14.3 10 <= mpg < 20 10 <= mpg < 20 #> 8 24.4 20 <= mpg 20 <= mpg #> 9 22.8 20 <= mpg 20 <= mpg #> 10 19.2 10 <= mpg < 20 10 <= mpg < 20 #> # … with 22 more rows
class(mtcars2$mpg_bin)
#> [1] "character"
class(mtcars2$mpg_bin_factor)
#> [1] "factor"
levels(mtcars2$mpg_bin_factor)
#> [1] "mpg < 10" "10 <= mpg < 20" "20 <= mpg"