Sorting Data Frames in R: Mastering the Order Function
Topic Overview
Today, we will delve into the usefulness of sorting data within a DataFrame using R's data.table or data.frame. The focus will be on using the order() function, covering both single and multi-column sorting and handling ties in our data.
Sample Dataset
Let's consider the following concise dataset of basketball players and their stats:
In this dataset, we observe a tie in the Points column between 'K. Durant' and 'K. Bryant'.
Learning How to Sort
We can sort the values in a DataFrame using the order() function in R.
This code sorts the DataFrame by the Points column in descending order. The negative sign clarifies that the values are to be sorted in descending order. Also note a comma , after the order function: this comma is a part of the indexing. We index rows by order(-df$Points), and the columns index is empty, meaning we select all the columns.
Now, we can easily identify the players with the highest average points scored.
Sorting by Multiple Columns
Sorting by Multiple Columns in Different Order
