Skip to main content
HomeTutorialsR Programming

Sorting Data in R

How to sort a data frame in R.
Apr 2024  · 2 min read

To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order. Here are some examples.

# sorting examples using the mtcars dataset

# sort by mpg
newdata <- mtcars[order(mpg),]

# sort by mpg and cyl
newdata <- mtcars[order(mpg, cyl),]

#sort by mpg (ascending) and cyl (descending)
newdata <- mtcars[order(mpg, -cyl),]


To practice, try this sorting exercise with the order() function.



Sorting in R using order() Tutorial

In this tutorial, you'll learn about sorting using order(). We will cover how to sort vectors using different parameters, sorting dataframes, and more.

Olivia Smith

6 min


Merging Datasets in R

In this tutorial, you'll learn to join multiple datasets in R.
Tom Jeon's photo

Tom Jeon

8 min


15 Easy Solutions To Your Data Frame Problems In R

Discover how to create a data frame in R, change column and row names, access values, attach data frames, apply functions and much more.
Karlijn Willems's photo

Karlijn Willems

35 min


Introduction to Data frames in R

This tutorial takes course material from DataCamp's Introduction to R course and allows you to practice data frames.
Ryan Sheehy's photo

Ryan Sheehy

5 min


Getting Started with the Tidyverse: Tutorial

Start analyzing titanic data with R and the tidyverse: learn how to filter, arrange, summarise, mutate and visualize your data with dplyr and ggplot2!
Hugo Bowne-Anderson's photo

Hugo Bowne-Anderson

21 min


Data Types in R

Learn about data types and their importance in a programming language. More specifically, learn how to use various data types like vector, matrices, lists, and dataframes in the R programming language.
Aditya Sharma's photo

Aditya Sharma

12 min

See MoreSee More