0

I had a dataset I was working with and I wanted to use order to sort values in a df column. But I did not get the right results. I checked format, and it was all numeric.

Then I loaded the mtcars data set built into R and also did not get the right results, i would like to know why that is:

enter image description here

lebelinoz
  • 4,890
  • 10
  • 33
  • 56
  • 1
    try sort() instead ?? – Zahiro Mor Mar 22 '18 at 13:44
  • 1
    See `?order` and try `mtcars[order(mtcars$hp),]`. – nicola Mar 22 '18 at 13:48
  • 2
    I find it implausible that they are not giving you the right results. More likely, you are not interpreting the results correctly. `order()` gives you a permutation of the indices, one which corresponds to the sort order. It doesn't directly sort the data. – John Coleman Mar 22 '18 at 13:48
  • Do you mean `mtcars[order(mtcars$hp),]`? – Prem Mar 22 '18 at 13:48
  • 1
    `order` returns the ranks of the vector. `sort` returns the sorted vector itself. Notice how `identical(mtcars$hp[order(mtcars$hp)], sort(mtcars$hp))` evaluates to `TRUE`. – ngm Mar 22 '18 at 13:49
  • 2
    @ngm, `order` does not return the ranks. `o <- order(x)` returns indexes such that `x[o]` is sorted and that is different than ranks. `order(o)` or `rank(x)` would be the ranks. – G. Grothendieck Mar 22 '18 at 13:51
  • 1
    Seems like a duplicate of: [Understanding the order() function](https://stackoverflow.com/q/2315601/4996248) – John Coleman Mar 22 '18 at 13:55
  • I was interpretting the results wrong. I should have used rank() function instead of order(). – Nauman Ahmed Mar 23 '18 at 14:43
  • Thank you all for the help. I looked into it more and understood the difference between order() and rank() – Nauman Ahmed Mar 23 '18 at 14:44

0 Answers0