case_when_factor: Turn case_when output into an ordered factor

Description Usage Arguments Value References Examples

View source: R/case_when_factor.R

Description

Turn case_when output into an ordered factor

Usage

1

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

 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)

KoderKow/kowr documentation built on July 19, 2021, 4:18 p.m.