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

R sort() Function - Sorting Vectors

R sort() Function - Sorting Vectors

R Language Examples R Language Examples

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:

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 order:"

)

print

(

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

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

]

)

The output of the code above is:

[1] "最低 3 个:"

[1] 68 72 78

[1] "最高 3 个:"

[1] 95 92 90

R Language Examples R Language Examples