Sort versus order

Does order() sort the values?

Yes, it sorts the elements based on their values (smallest first, largest last) but instead of returning these sorted values it returns the indices of the sorted elements.

Whereas sort() sorts the elements in exactly the same way but this function will return the sorted values.

Sort or order data frames?

You can sort() a column of a data frame:

sort(mtcars$mpg)

But you cannot use mtcars as input:

sort(mtcars)

Gives an error. When you look in the documentation you see that the input (x) is supposed to be a vector or a factor.

Sort() works nice on a vector but for data frames order() is much more useful since it returns indices. You can use these indices inside [ ] to sort the rows of the data frame.

Can you use sort inside[ ] ?

mtcars[sort(mtcars$mpg), ]

Doesn’t work. It gives strange results because the output of

sort(mtcars$mpg)

cannot be used inside [ ]

The only things that can be used inside [ ] are indices, labels, or logical operations. The output of sort() is neither of those, it’s sorted values.

Sort in decreasing order

By default both sort and order will sort in increasing order (low -> high).

To order in decreasing order:

  • set the decreasing argument to TRUE
    mtcars[order(mtcars$mpg, decreasing=TRUE), ]
  • use the – sign in front of the name of the column you want to sort on
    mtcars[order(-mtcars$mpg), ]

To sort in decreasing order you have to use the decreasing argument. The – sign does not work for sort().