Working on my personal project today, I had to figure out how to sort out a data frame, and very little straightforward information exists about doing this, so I ended up figuring it out myself from a gaggle of incomplete internet posts.

The key to doing this is using both order() and with(). Order returns the ID numbers of how the vector should look. With allows you to rewrite a new data frame.

My code ended up looking like this:


country.trim <- country.trim[with(country.trim, order(-income)),]

I started with my original variable country.trim which was a dataframe containing variables country, income, and debt. I desired to sort the countries by income in descending order. So what we do is sort of "play back" the existing dataframe into its sorted form. with() country.trim, we take the order(). order() will only sort in ascending order, so we make income negative. order() gives us a vector of what the new row names should be, and we play that back into the new country.trim variable.

In the more general case, this is what you want to do:

dataFrame.sorted <- dataFrame.original[ with(dataFrame.original, order(sortCriteria1, sortCriteria2,....)) , ]

Do this where each sortCriteria is one of the members of the data frame. For example, in the example of my code, I don't use order(-country$income). You can have as many sort criteria as you want, and remember to prepend a minus sign to any variables that should be sorted in descending order.