tidyverse / forcats

🐈🐈🐈🐈: tools for working with categorical variables (factors)
https://forcats.tidyverse.org/
Other
555 stars 127 forks source link

fct_relevel and fct_recode: add option to turn off warnings #287

Closed DagHjermann closed 1 year ago

DagHjermann commented 3 years ago

I would be nice to have to option to turn off warnings by adding the argument warn = TRUE.

I work with surveys where people have the option of choosing "Other" in a multiple choice question. I'd like that to be the last category in plots, but sometimes no-one has chosen "Other", and I don't want to have a warning in my knitted Markdown doc every time that happens. So an option such as this would be nice:

factor(Alternative) %>% fct_relevel("Other", after = Inf, warn = FALSE)

I have implemented this myself by adding an if:

    if (warn)
      warning("Unknown levels in `f`: ", paste(unknown, collapse = ", "), call. = FALSE)

It should not break any code as long as the default is TRUE.

hadley commented 1 year ago

I think this is a good place to write your own function:

other_last <- function(f) {
  if ("Other" %in% levels(f)) {
    fct_relevel(f, after = Inf)
  } else {
    f
  }
}