R sort() Function - Sorting Vectors
The R sort() function is used to sort the 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 How NA values are handled: TRUE places them at the end, FALSE at the beginning, and NA removes them.
Example
Numeric sorting
x
<-
c
(
12
,
27
,
3
,
4.2
,
2
,
54
,
21
,
4
,
2
)
(
"Ascending order:"
)
(
sort
(
x
)
)
(
"Descending order:"
)
(
sort
(
x, decreasing
=
TRUE
)
)
Character sorting
fruits
<-
c
(
"banana"
,
"apple"
,
"cherry"
,
"blueberry"
)
(
"Alphabetical order:"
)
(
sort
(
fruits
)
)
The output of the code above is:
[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 get the first n largest or smallest values:
Example
scores
<-
c
(
85
,
92
,
78
,
95
,
88
,
72
,
90
,
68
,
82
,
89
)
The 3 smallest scores
(
"Lowest 3:"
)
(
sort
(
scores
)
[
1
:
3
]
)
The 3 largest scores
sorted_desc
<-
sort
(
scores, decreasing
=
TRUE
)
(
"Highest 3:"
)
(
sorted_desc
[
1
:
3
]
)
The output of the code above is:
[1] "最低 3 个:"
[1] 68 72 78
[1] "最高 3 个:"
[1] 95 92 90
R Language Examples