Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R order() Function - Getting Sort Indices

R order() Function - Getting Sort Indices

R Language Examples R Language Examples

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:

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

)

print

(

"Sorted indices:"

)

print

(

idx

)

Use the indices to get the sorted values and corresponding names

print

(

"Ascending by score:"

)

print

(

x

[

idx

]

)

sort directly returns the sorted values (for comparison)

print

(

"sort direct result:"

)

print

(

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

)

,

]

print

(

"Descending by score:"

)

print

(

df_sorted

)

Multi-condition sorting: first by age, then by score

df_sorted2

<-

df

[

order

(

df

$age,

df

$score

)

,

]

print

(

"By age then by score:"

)

print

(

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 R Language Examples