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 
1

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much... What if the order is not necessarily alphabetical. But for example Var1: bbb, ccc, aaa and Var2: yyy, xxx, zzz?
Then you should use a factor variable and order the levels as desired. You can take look here.
Great, thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.