R Func Sort
# R sort() Function - Sort Vectors
[ R Language Examples](#)
The R sort() function is used to sort elements in a vector.
sort() can directly return the sorted vector, supporting ascending, descending, and partial sorting.
The syntax of the sort() function is as follows:
sort(x, decreasing = FALSE, na.last = NA)
**Parameter Description:**
* **x** Input vector.
* **decreasing** Whether to sort in descending order, defaults to FALSE (ascending).
* **na.last** NA value handling: TRUE puts them at the end, FALSE puts them at the beginning, NA removes them.
## Example
# Numeric Sorting
x <-c(12, 27, 3, 4.2, 2, 54, -21, 4, -2)
print("Ascending Order:")
print(sort(x))
print("Descending Order:")
print(sort(x, decreasing = TRUE))
# Character Sorting
fruits <-c("banana", "apple", "cherry", "blueberry")
print("Alphabetical Sorting:")
print(sort(fruits))
Executing the above code outputs the following result:
"Ascending Order:" -21.0 -2.0 2.0 3.0 4.0 4.2 12.0 27.0 54.0 "Descending Order:" 54.0 27.0 12.0 4.2 4.0 3.0 2.0 -2.0 -21.0 "Alphabetical Sorting:" "apple" "banana" "blueberry" "cherry"
sort() can also be used to get the top n maximum or minimum values:
## Example
scores <-c(85, 92, 78, 95, 88, 72, 90, 68, 82, 89)
# Smallest 3 item scores
print("Lowest 3 items:")
print(sort(scores)[1:3])
# Largest 3 item scores
sorted_desc <-sort(scores, decreasing = TRUE)
print("Highest 3 items:")
print(sorted_desc[1:3])
Executing the above code outputs the following result:
"Lowest 3 items:" 68 72 78 "Highest 3 items:" 95 92 90
[ R Language Examples](#)
YouTip