rtidyverser-factor

Error out if filtering for a non-existent level


Given this factor variable:

library(tidyverse)
a <- factor(c(1,1,1,2,2), levels=c(1,2), labels=c("Male", "Female"))

I want this to error out because Females is not a valid level:

a %>% .[.=="Male"|.=="Females"]

How can I do that?


Solution

  • forcats::fct_match() errors when levels aren't present, so you can do:

    library(forcats)
    
    a <- factor(c(1,1,1,2,2), levels=c(1,2), labels=c("Male", "Female"))
    
    a %>% .[fct_match(., c("Male", "Females"))]
    
    #> Error in `fct_match()`:
    #> ! All `lvls` must be present in `f`.
    #> ℹ Missing levels: "Females"
    
    a %>% .[fct_match(., c("Male", "Female"))]
    
    #> [1] Male   Male   Male   Female Female
    #> Levels: Male Female