I want to order groups in a dplyr tibble by using an aggregation function. Let's say I have this data:
library(dplyr)
df <- tibble(
g = c(0, 0, 1, 1, 2, 2, 2),
x = c(0, 1, 1, 2, -2, -3, -3)
)
Where g
is the grouping variable. If I want to sort using the mean of x, I would expect g=2
observations be on top, then g=0
and then g=1
. The first thing that comes to mind is to:
df %>%
group_by(g) %>%
arrange(mean(x))
But this is not sorted the way I expected:
# A tibble: 7 x 2
# Groups: g [3]
g x
<dbl> <dbl>
1 0 0
2 0 1
3 1 1
4 1 2
5 2 -2
6 2 -3
7 2 -3
Instead, I would expect to have something like:
# A tibble: 7 x 2
# Groups: g [3]
g x
<dbl> <dbl>
1 2 -2
2 2 -3
3 2 -3
4 0 0
5 0 1
6 1 1
7 1 2
is there a tidy way to do this operation?