Introduction
In this blog, we shall learn to sort a Data Frame in R. To sort a data frame we will first learn what the data frame is, how to create, print the data frame in R and then how to sort that data frame in R.
Let's begin...
Creating Data Frame In R
Data Frame in R is itself an object which stores data in row and column-wise just like Excel format. Here a single column contains only one type of elements but different columns can contain different data types of elements.

The above image shows one of the sample data frame structures in R.
Now we will create a data frame in R. For creating a data frame in R we will run the below R script in R studio. It will create a data frame of names df.CustomerDetails. Here one thing is to remember: dot (.) is nothing more than a separator we use to separate a longer name in R.
- #Creating three vectors for the data frame creation df.AddressDetails
- CustomerID <- c(1, 77, 2, 85, 65)
- CustomerName <- c("Alfreds Futterkiste", "Ana Trujillo Emparedados C-245",
- "Antonio Moreno Taquer??a", "Zachariah E. Somers",
- "Jonathan G. Steck")
- Address <- c("Obere Str. 57", "Avda. de la Constituci??n 2222",
- "Mataderos 2312", "1181 Lawman Avenue", "Mellingburgredder 82")
- City <- c("Berlin", "Alexandria", "M??xico D.F.", "Alexandria","Herzogenaurach")
- PostalCode <- c(12209, 5021, 5023, 14850, 57860)
- Country <- c("Germany", "Mexico", "Mexico", "USA", "Germany")
- #Using above vector to create the data frame - df.AddressDetails
- df.CustomerDetails <- data.frame(CustomerID, CustomerName, Address, City,

Sorting Data Frame In R
To sort a data frame in R, we use the order() function. As in most of the languages, R has also the default value of sorting is ASCENDING. We can sort a data frame in descending order by passing a prefix sign minus (-) before the variable name.
The below example shows how to use the order() function in R.
- #Sorting Based On the Customer ID
- df.CustomerDetails[order(df.CustomerDetails$CustomerID), ]

As when we only print the passed argument as shown below it gives the output as 1 3 5 2 4 which are the index of the CustomerID values in ascending order.
- order(df.CustomerDetails$CustomerID)
- [1] 1 3 5 2 4
- df.CustomerDetails[order(-df.CustomerDetails$CustomerID), ]
Summary
In this blog, we learned about the data frame in R, the definition, how to create and sort the data frame in R. To learn more about the data frame, you can follow my article on C-sharp Corner written on the R language.
Hope you learned and enjoyed this blog on R.

PankajPosted Oct 29, 2020, 10:36 PM
Thanks suraj sir
Sourav Kumar DasPosted Dec 17, 2019, 10:48 PM
Nice and useful article Sir.