Description Usage Arguments Value References Examples
View source: R/case_when_factor.R
Turn case_when output into an ordered factor
1 |
... |
< 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | library(dplyr)
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
class(mtcars2$mpg_bin)
class(mtcars2$mpg_bin_factor)
levels(mtcars2$mpg_bin_factor)
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.