Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between sort(), rank(), and order() [duplicate]

What is the difference between sort(), rank(), and order() in R.

Can you explain with examples?

like image 319
Amit Gupta Avatar asked Jan 03 '19 06:01

Amit Gupta


1 Answers

sort() sorts the vector in an ascending order.

rank() gives the respective rank of the numbers present in the vector, the smallest number receiving the rank 1.

order() returns the indices of the vector in a sorted order.

for example: if we apply these functions are applied to the vector - c (3, 1, 2, 5, 4)

sort(c (3, 1, 2, 5, 4)) will give c(1,2,3,4,5)

rank(c (3, 1, 2, 5, 4)) will give c(3,1,2,5,4)

order(c (3, 1, 2, 5, 4)) will give c(2,3,1,5,4). if you put these indices in this order, you will get the sorted vector. Notice how v[2] = 1, v[3] = 2, v[1] = 3, v[5] = 4 and v[4] = 5

also there is a tie handling method in R. If you run rank(c (3, 1, 2, 5, 4, 2)) it will give Rank 1 to 1, since there are two 2 present R will rank them on 2 and 3 but assign Rank 2.5 to each of them, next 3 will get Rank 4.0, so

rank(c (3, 1, 2, 5, 4, 2)) will give you output [4.0 1.0 2.5 6.0 5.0 2.5]

Hope this is helpful.

like image 123
Amit Gupta Avatar answered Oct 18 '22 23:10

Amit Gupta