1

How to sort a matrix based on columns and its values in R?

For Example : I have a matrix like this :

ID  Name    Number
1   Bat     43
2   Apple   42
4   Dog     41
5   Ball    41
6   Cat     40

I want to sort the matrix based on the values of the column Number. If two values are same then it should sort based on the column Name. The exepcted output should be

ID  Name    Number
6   Cat     40
5   Ball    41
4   Dog     41
2   Apple   42
1   Bat     43

Since, Ball and Dog has same value for the column Number . They are sorted according to the column Name(that is alphabetically). Can someone help me in doing this?

Minions
  • 1,263
  • 9
  • 26

1 Answers1

0

using order:

df[with(df, order(Number, Name)), ]
jeremycg
  • 22,778
  • 5
  • 58
  • 69