0
0
R Programmingprogramming~5 mins

Sorting with order() in R Programming

Choose your learning style9 modes available
Introduction
Sorting with order() helps you arrange data in a specific order, like from smallest to largest, so you can find or compare things easily.
When you want to list students by their scores from highest to lowest.
When you need to organize dates in chronological order.
When you want to sort names alphabetically.
When you want to sort one list based on the order of another related list.
Syntax
R Programming
order(x, decreasing = FALSE, na.last = TRUE)
x is the vector or data you want to sort by.
decreasing = FALSE means sort from smallest to largest; set to TRUE for largest to smallest.
Examples
Returns the positions that would sort x in ascending order.
R Programming
x <- c(5, 2, 9, 1)
order(x)
Returns positions to sort x from largest to smallest.
R Programming
x <- c(5, 2, 9, 1)
order(x, decreasing = TRUE)
Sorts names alphabetically by their positions.
R Programming
names <- c("Anna", "John", "Zara")
order(names)
Sorts names based on scores from lowest to highest.
R Programming
scores <- c(90, 85, 95)
names <- c("Bob", "Alice", "Carol")
names[order(scores)]
Sample Program
This program sorts the names based on their scores from highest to lowest using order().
R Programming
scores <- c(88, 95, 70, 100)
names <- c("John", "Alice", "Bob", "Diana")
# Get order of scores from highest to lowest
sorted_positions <- order(scores, decreasing = TRUE)
# Use order to sort names by scores
sorted_names <- names[sorted_positions]
print(sorted_names)
OutputSuccess
Important Notes
order() returns the positions (indexes) that sort the data, not the sorted data itself.
You can use the result of order() to rearrange other related data in the same order.
By default (na.last = TRUE), NA values are placed last; use na.last = FALSE to place them first or na.last = NA to omit them.
Summary
order() helps find the order of elements to sort data.
Use order() to sort one vector or to reorder related vectors.
Set decreasing = TRUE to sort from largest to smallest.