fct_case_when: Factor case_when

Description Usage Arguments Details Value Examples

View source: R/fct_case_when.R

Description

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

1

Arguments

...

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

Details

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

Value

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

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
library(dplyr)
partysum <- with(dec13_excerpt, fct_case_when(party == "Republican" ~ "Rep/Lean Rep",
                          party == "Democrat"  ~ "Dem/Lean Dem",
                          partyln == "Republican" ~ "Rep/Lean Rep",
                          partyln == "Democrat" ~ "Dem/Lean Dem",
                          TRUE ~ partyln)
                          )

# Compare to normal case_when() and then factor(), which will arrange the levels in
# unwanted alphabetical order

partysum <- with(dec13_excerpt, factor(case_when(party == "Republican" ~ "Rep/Lean Rep",
                             party == "Democrat"  ~ "Dem/Lean Dem",
                             partyln == "Republican" ~ "Rep/Lean Rep",
                             partyln == "Democrat" ~ "Dem/Lean Dem",
                             TRUE ~ as.character(partyln))))

pewresearch/pewmethods documentation built on March 27, 2020, 7:22 p.m.