From the course: R for Data Science: Lunch Break Lessons

Unlock this course with a free trial

Join today to access over 22,600 courses taught by industry experts.

Sort a data frame by multiple columns

Sort a data frame by multiple columns

- [Mark] I've been asked by more than one person, "How do you sort a data frame on multiple columns?" And let's step through that process real quick. I've created a vector called myWeights. It's actually a data frame, and it's got the ChickWeight data in it. Let's take a quick look at that. Here it is weight, Time, Chick, and Diet, and it's unsorted. And in line six I sort it by the weight column. And the way that I'm doing that is you'll see that I've specified that I want to sort myWeights, and I use the order column to output the result of ordering myWeights$weight. Now this will return a new numeric order. And that new numeric order is applied against the rows of myWeights, and then saved into order_myweights. Let's take a look at the result of that. And you can see that the weight column's now sorted. 35, 39, 40, and on. But you'll notice that none of the other columns are sorted. So now how do I sort by two…

Contents