I often make a factor variable that I want to retain the order of the variable it comes from. I feel like I should be able to do this by taking the average within each group of the new categorical variable, then using that as the ordering variable in fct_reorder, but it doesn't seem to work. Here is a simple example:
library(tidyverse)
test_data <- mtcars %>%
mutate(mpg_cat=case_when(mpg>20 ~ "More than 20",
mpg<=20 & mpg>=15 ~ "15-20",
mpg<15 ~ "Less than 15")) %>%
group_by(mpg_cat) %>%
mutate(avg_mpg=mean(mpg),
mpg_cat=fct_reorder(mpg_cat,avg_mpg))
levels(test_data$mpg_cat) #Want the order to be less than 15, 15-20, More than 20