R order() Function - Getting Sort Indices
The R order() function returns the index positions of each sorted element in the original vector.
Unlike sort(), which returns the sorted values, order() returns the sorting permutation, which is very useful for sorting data frames.
The syntax of the order() function is as follows:
order(x, decreasing = FALSE, na.last = TRUE)
Parameter Description:
-
x Input vectors (multiple vectors can be passed for multi-condition sorting).
-
decreasing Whether to sort in descending order, FALSE by default.
-
na.last Position of NA values.
Example
x
<-
c
(
50
,
20
,
30
,
10
,
40
)
names
(
x
)
<-
c
(
"Zhang San"
,
"Li Si"
,
"Wang Wu"
,
"Zhao Liu"
,
"Qian Qi"
)
order returns the sort indices
idx
<-
order
(
x
)
(
"Sorted indices:"
)
(
idx
)
Use the indices to get the sorted values and corresponding names
(
"Ascending by score:"
)
(
x
[
idx
]
)
sort directly returns the sorted values (for comparison)
(
"sort direct result:"
)
(
sort
(
x
)
)
The output of the code above is:
[1] "排序后的索引:"
[1] 4 2 3 5 1
[1] "按成绩升序:"
赵六 李四 王五 钱七 张三
10 20 30 40 50
[1] "sort 直接结果:"
赵六 李四 王五 钱七 张三
10 20 30 40 50
order() is very practical for sorting data frames:
Example
Create a data frame
df
<-
data.frame
(
Name
=
c
(
"Zhang San"
,
"Li Si"
,
"Wang Wu"
,
"Zhao Liu"
,
"Qian Qi"
)
,
Age
=
c
(
25
,
30
,
22
,
28
,
26
)
,
Score
=
c
(
88
,
92
,
76
,
85
,
90
)
)
Sort by score in descending order
df_sorted
<-
df
[
order
(
df
$score, decreasing
=
TRUE
)
,
]
(
"Descending by score:"
)
(
df_sorted
)
Multi-condition sorting: first by age, then by score
df_sorted2
<-
df
[
order
(
df
$age,
df
$score
)
,
]
(
"By age then by score:"
)
(
df_sorted2
)
The output of the code above is:
[1] "按成绩降序排列:"
姓名 年龄 成绩
2 李四 30 92
5 钱七 26 90
1 张三 25 88
4 赵六 28 85
3 王五 22 76
[1] "先按年龄再按成绩:"
姓名 年龄 成绩
3 王五 22 76
1 张三 25 88
5 钱七 26 90
4 赵六 28 85
2 李四 30 92
R Language Examples