Turn case_when output into an ordered factor
case_when_factor(...)
... | < 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
|
---|
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.
https://stackoverflow.com/questions/49572416/r-convert-to-factor-with-order-of-levels-same-with-case-when
#> #>#>#> #>#>#> #>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#> [1] "character"#> [1] "factor"#> [1] "mpg < 10" "10 <= mpg < 20" "20 <= mpg"