R sort() Function - Sort a Vector

R 语言实例R Language Examples

The R sort() function is used to sort elements in a vector.

sort() can directly return the sorted vector, supporting ascending order, descending order, and partial sorting.

The syntax of the sort() function is as follows:

sort(x, decreasing = FALSE, na.last = NA)

Parameter description:

  • xInput vector.

  • decreasingWhether to sort in descending order; default is FALSE (ascending).

  • na.lastHow to handle NA values: TRUE places them at the end, FALSE places them at the beginning, and "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("Sort alphabetically:")
print(sort(fruits))

Executing the above code produces the following output:

[1] "升序排列:"
[1] -21.0  -2.0   2.0   3.0   4.0   4.2  12.0  27.0  54.0
[1] "降序排列:"
[1] 54.0 27.0 12.0  4.2  4.0  3.0  2.0 -2.0 -21.0
[1] "按字母排序:"
[1] "apple"     "banana"    "blueberry" "cherry"

sort() can also obtain the top n maximum or minimum values:

Example

scores <- c(85, 92, 78, 95, 88, 72, 90, 68, 82, 89)

# The 3 smallest scores
print("Lowest 3:")
print(sort(scores)[1:3])

# The 3 largest scores
sorted_desc <- sort(scores, decreasing = TRUE)
print("Highest 3:")
print(sorted_desc[1:3])

Executing the above code produces the following output:

[1] "最低 3 个:"
[1] 68 72 78
[1] "最高 3 个:"
[1] 95 92 90

R 语言实例R Language Examples

Other extensions