tidyverse/forcats

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

cgoo4 opened this issue · 1 comments

cgoo4 commented

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)

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 😄