Context: I need to use factor order to make arrange
diplays a table in a certain way. I.e I want to get a "Total" line at the end of each group.
Problem: using fct_relevel
I acheive the expected output only within the first group.
Repex:
library(dplyr)
library(forcats)
total_masses <- starwars %>%
group_by(species) %>%
summarise(mass = sum(mass),
name = "Total mass")
df <- bind_rows(starwars, total_masses) %>%
select(species, name, mass) %>%
group_by(species) %>%
mutate(name = fct_relevel(name, "Total mass", after = Inf)) %>%
arrange(mass, name, species)
df
#> # A tibble: 125 x 3
#> # Groups: species [38]
#> species name mass
#> <chr> <fct> <dbl>
#> 1 Aleena Ratts Tyerell 15
#> 2 Aleena Total mass 15
#> 3 Yoda's species Total mass 17 # I expect this line to be at the end of the Yoda's species group
#> 4 Yoda's species Yoda 17
#> 5 Ewok Total mass 20
#> 6 Ewok Wicket Systri Warrick 20
#> 7 Droid R2-D2 32
#> 8 Droid R5-D4 32
#> 9 Dug Total mass 40
#> 10 Dug Sebulba 40
#> # ... with 115 more rows
Created on 2021-05-31 by the reprex package (v2.0.0)
I expect each Total mass
to be at the end of each species
category:
species name mass
<chr> <fct> <dbl>
1 Aleena Ratts Tyerell 15
2 Aleena Total mass 15
3 Yoda's species Yoda 17
4 Yoda's species Total mass 17
etc...
I feel like the solution is very obvious but I was not able to find the right keywords to solve it... Any tip is welcome!