tidyverse / forcats

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

`fct_relevel` lumped, e.g. "Other___", levels after using `reorder_within` #308

Closed cgoo4 closed 1 year ago

cgoo4 commented 2 years ago

When fct_relevel is used after reorder_within, it would be useful if there were a way to generalise positioning a lumped grouping. In the example below, it would mean replacing the first commented line (which delivers the desired result) with something like the next commented line (which is not currently supported).

library(tidyverse)
library(tidytext)

DF <- tribble(
  ~Item, ~Color, ~Sales,
  "Cars", "Other", 500,
  "Cars", "Green", 200,
  "Cars", "Red", 75,
  "Cars", "Blue", 100,
  "Trucks", "Other", 150,
  "Trucks", "Black", 50,
  "Trucks", "Red", 100,
  "Trucks", "Blue", 25
) 

DF %>%
  mutate(
    Color = reorder_within(Color, Sales, Item),
    Color = fct_relevel(Color, "Other___Cars", "Other___Trucks") # Replace this
    # Color = fct_relevel(Color, ~ str_starts(., "Other___")) # With this
    ) %>% 
  ggplot(aes(Color, Sales)) +
  geom_col() +
  scale_x_reordered() +
  facet_wrap(~ fct_rev(Item), ncol = 1, scales = "free_y") +
  coord_flip() +
  theme_minimal()

Created on 2022-05-22 by the reprex package (v2.0.1)

hadley commented 1 year ago

I think this is out of scope for forcars, since it doesn't currently provide tools for lumped factors. Even though I'm closing this issue, I really appreciate the feedback, and hope you'll continue to contribute in the future πŸ˜„