How to order rows according to two conditions?
Given data:
df
Var1 Var2 Values
aaa x 4
aaa y 7
aaa z 6
bbb x 9
bbb y 21
bbb z 13
ccc x 4
ccc y 19
ccc z 0
Goal: Order the rows according to Var1 and Var2
First step: ordering rows according to Var1
df %>% dplyr::arrange(match(Var1, c("bbb", "ccc", "aaa")))
Var1 Var2 Values
ccc x 4
ccc y 19
ccc z 0
bbb x 9
bbb y 21
bbb z 13
aaa x 4
aaa y 7
aaa z 6
Second step: How to order Var2 while keeping the order of Var1? How to get the following output?
Var1 Var2 Values
ccc z 0
ccc y 19
ccc x 4
bbb z 13
bbb y 21
bbb x 9
aaa z 6
aaa y 7
aaa x 4
Solution 1:
You can use arrange
and desc
df %>%
arrange(desc(Var1), desc(Var2))
Var1 Var2 Values
1 ccc z 0
2 ccc y 19
3 ccc x 4
4 bbb z 13
5 bbb y 21
6 bbb x 9
7 aaa z 6
8 aaa y 7
9 aaa x 4