Skip to contents

A 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.

Usage

fct_case_when(...)

Arguments

...

A sequence of two-sided formulas consistent with dplyr::case_when.

Value

The output of dplyr::case_when(), as class "factor" and ordered however you wanted it.

Details

Unlike dplyr::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.

Examples


library(dplyr)
#> 
#> 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
iris_fct <-
  iris %>%
  mutate(width_factors = fct_case_when(
    Sepal.Width > 5 ~ "Above 5",
    Sepal.Width <= 5 ~ "Equal or below 5"
  ))

class(iris_fct$width_factors)
#> [1] "factor"
levels(iris_fct$width_factors)
#> [1] "Above 5"          "Equal or below 5"


iris_fct <-
  iris %>%
  mutate(width_factors = fct_case_when(
    Sepal.Width > 6 ~ "Above 6",
    Sepal.Width > 5 ~ "Above 5",
    Sepal.Width > 4 ~ "Above 4",
    Sepal.Width > 3 ~ "Above 3",
    Sepal.Width > 2 ~ "Above 2",
    Sepal.Width > 1 ~ "Above 1",
    TRUE ~ "Below 1"
  ))

class(iris_fct$width_factors)
#> [1] "factor"
levels(iris_fct$width_factors)
#> [1] "Above 6" "Above 5" "Above 4" "Above 3" "Above 2" "Above 1" "Below 1"