Open In App

How to sort R DataFrame by the contents of a column ?

Last Updated : 07 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will discuss how to sort DataFrame by the contents of the column in R Programming language. We can use the order() function for the same. order() function with the provided parameters returns a permutation that rearranges its first argument into ascending or descending order, breaking ties by further arguments. 

Syntax: order(x, decreasing = TRUE/FALSE, na.last = TRUE or FALSE, method = c("auto", "shell", "quick", "radix"))

Parameters:

  • x: data-frames, matrices, or vectors
  • decreasing: TRUE then sort in descending order / FALSE then sort in ascending order.
  • na.last: TRUE then NA indices are put at last / FALSE then NA indices are put first.
  • method: sorting method.

Return: returns a permutation that rearranges its first argument into ascending or descending order of the data frame, vector, matrix, etc.

Example1:

R
gfg_data <- data.frame(
  Country = c("France","Spain","Germany","Spain","Germany",
              "France","Spain","France","Germany","France"), 
  
  age = c(44,27,30,38,40,35,52,48,45,37),
  
  salary = c(6000,5000,7000,4000,8000), 
  
  Purchased=c("No","Yes","No","No","Yes","Yes","No","Yes",
              "No","Yes")
)

gfg_data[order(gfg_data$Country),]

Output:

r sort dataframe 1

Example2:

R
gfg_data <- data.frame(
  Country = c("France","Spain","Germany","Spain","Germany",
              "France","Spain","France","Germany","France"), 
    
  age = c(44,27,30,38,40,35,52,48,45,37),
    
  salary = c(6000,5000,7000,4000,8000), 
    
  Purchased=c("No","Yes","No","No","Yes","Yes","No","Yes",
              "No","Yes")
)

gfg_data[order(gfg_data$age),]

  

Output:


 

R sort dataframe 2


 


Next Article

Similar Reads