1

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
Phil
  • 7,287
  • 3
  • 36
  • 66
must
  • 11
  • 1
  • Does this answer your question? [Sort (order) data frame rows by multiple columns](https://stackoverflow.com/questions/1296646/sort-order-data-frame-rows-by-multiple-columns) – KoenV Jan 20 '22 at 16:00

1 Answers1

3

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
Maël
  • 45,206
  • 3
  • 29
  • 67
  • Thank you very much... What if the order is not necessarily alphabetical. But for example Var1: bbb, ccc, aaa and Var2: yyy, xxx, zzz? – must Jan 21 '22 at 13:14
  • Then you should use a factor variable and order the levels as desired. You can take look [here](https://stackoverflow.com/questions/9391910/sort-a-data-frame-manually-using-non-numeric-column). – Maël Jan 21 '22 at 13:27
  • Great, thank you! – must Jan 24 '22 at 11:40