Sorting Data
Sorting is a fundamental operation in data analysis. It allows you to organize your dataset based on one or more variables - such as price, mileage, or year. This makes it easier to identify trends, outliers, or simply view the data in a meaningful order.
Sorting in Ascending Order
Base R
You can use the order()
function to sort a dataset by column values. By default, this returns the data in ascending order.
df_sorted_price_base <- df[order(df$selling_price), ]
dplyr
Sorting can be done using the arrange()
function, which also defaults to ascending order.
df_sorted_price_dplyr <- df %>%
arrange(selling_price)
Sorting in Descending Order
Base R
To sort in descending order, place a negative sign (-
) in front of the column inside the order()
function.
df_sorted_price_desc <- df[order(-df$selling_price), ]
dplyr
You can use the desc()
function inside arrange()
to reverse the order.
sorted_price_desc_dplyr <- df %>%
arrange(desc(selling_price))
Sorting by Multiple Columns
It is possible to sort by more than one column to create a prioritized order. For example, you might sort first by fuel type (alphabetically) and then by selling price in descending order.
Base R
df_sorted <- df[order(df$fuel, -df$selling_price), ]
dplyr
df_sorted_dplyr <- df %>%
arrange(fuel, desc(selling_price))
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Awesome!
Completion rate improved to 4
Sorting Data
Swipe to show menu
Sorting is a fundamental operation in data analysis. It allows you to organize your dataset based on one or more variables - such as price, mileage, or year. This makes it easier to identify trends, outliers, or simply view the data in a meaningful order.
Sorting in Ascending Order
Base R
You can use the order()
function to sort a dataset by column values. By default, this returns the data in ascending order.
df_sorted_price_base <- df[order(df$selling_price), ]
dplyr
Sorting can be done using the arrange()
function, which also defaults to ascending order.
df_sorted_price_dplyr <- df %>%
arrange(selling_price)
Sorting in Descending Order
Base R
To sort in descending order, place a negative sign (-
) in front of the column inside the order()
function.
df_sorted_price_desc <- df[order(-df$selling_price), ]
dplyr
You can use the desc()
function inside arrange()
to reverse the order.
sorted_price_desc_dplyr <- df %>%
arrange(desc(selling_price))
Sorting by Multiple Columns
It is possible to sort by more than one column to create a prioritized order. For example, you might sort first by fuel type (alphabetically) and then by selling price in descending order.
Base R
df_sorted <- df[order(df$fuel, -df$selling_price), ]
dplyr
df_sorted_dplyr <- df %>%
arrange(fuel, desc(selling_price))
Thanks for your feedback!