Ah, now I see. Nice use of weighted.mean for filtering at the same time! As far as I know, fct_reorder and fct_reorder2 are working the way you think they are. You can shorten the code further by reordering within facet_wrap:
mtcars %>%
ggplot(aes(factor(gear), hp)) +
stat_summary(fun = mean) +
facet_wrap(~ fct_reorder2(factor(cyl), hp, gear==3, weighted.mean, .desc=TRUE))
To check what fct_reorder2 is doing, you could create a simpler data frame and compare the output of an explicit reordering with the output of fct_reorder2. For example:
library(tidyverse)
d = data.frame(cyl = rep(1:3, each=6),
gear = rep(1:3, 6),
hp = c(10, 5, 1, 9, 4, 0,
5, 1, 10, 4, 0, 9,
1, 10, 5, 0, 9, 4)) %>%
arrange(gear)
map(1:3, ~ {
list(
cyl.order = d %>%
mutate(cyl=fct_reorder2(factor(cyl), hp, gear==.x, weighted.mean, .desc=TRUE)) %>%
pull(cyl) %>% levels,
check.cyl.order = d %>%
group_by(cyl) %>%
summarise(hp.mean = weighted.mean(hp, gear==.x)) %>%
arrange(desc(hp.mean))
)
})
#> [[1]]
#> [[1]]$cyl.order
#> [1] "1" "2" "3"
#>
#> [[1]]$check.cyl.order
#> # A tibble: 3 x 2
#> cyl hp.mean
#> <int> <dbl>
#> 1 1 9.5
#> 2 2 4.5
#> 3 3 0.5
#>
#>
#> [[2]]
#> [[2]]$cyl.order
#> [1] "3" "1" "2"
#>
#> [[2]]$check.cyl.order
#> # A tibble: 3 x 2
#> cyl hp.mean
#> <int> <dbl>
#> 1 3 9.5
#> 2 1 4.5
#> 3 2 0.5
#>
#>
#> [[3]]
#> [[3]]$cyl.order
#> [1] "2" "3" "1"
#>
#> [[3]]$check.cyl.order
#> # A tibble: 3 x 2
#> cyl hp.mean
#> <int> <dbl>
#> 1 2 9.5
#> 2 3 4.5
#> 3 1 0.5
Created on 2020-11-30 by the reprex package (v0.3.0)