How to sort R DataFrame by the contents of a column ?
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:
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:
Please Login to comment...