# [R] Question about base::rank results

David L Carlson dcarlson at tamu.edu
Mon Apr 27 23:14:35 CEST 2015

```Apologies if this belabors the point, but let's look at your second example to see why order and rank are different:

> x <- c(12,34,15,77,78,22)
> names(x) <- 1:6
> x
1  2  3  4  5  6
12 34 15 77 78 22

I've added names to the values so we can watch how they change. If we sort the numbers we get them in increasing order with their original indices:

> sort(x)
1  3  6  2  4  5
12 15 22 34 77 78

The values in are order and the names show where each value came from originally. That sequence of index values is exactly what order(x) gives you:

> order(x)
[1] 1 3 6 2 4 5
> x[order(x)]
1  3  6  2  4  5
12 15 22 34 77 78

The rank function gives you the relative size of the value, not its position in the original vector:

> rank(x)
1 2 3 4 5 6
1 4 2 5 6 3
> x[rank(x)]
1  4  2  5  6  3
12 77 34 78 22 15

The second value has rank 4, but that is not its index which is 2. The value with index 4 is 77 so it shows up in the second position.

-------------------------------------
David L Carlson
Department of Anthropology
Texas A&M University
College Station, TX 77840-4352

-----Original Message-----
From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of J Robertson-Burns
Sent: Monday, April 27, 2015 2:34 PM
To: Giorgio Garziano; r-help at r-project.org
Subject: Re: [R] Question about base::rank results

There is a blog post on this topic:

http://www.portfolioprobe.com/2012/07/26/r-inferno-ism-order-is-not-rank/

Pat

On 26/04/2015 09:17, Giorgio Garziano wrote:
> Hi,
>
> I cannot understand why rank(x) behaves as outlined below.
> Based on the results of first x vector values ranking, which is as expected in my opinion,
> I cannot explain the following results.
>
>> x <- c(12,34,15,77,78)
>> x[rank(x)]
> [1] 12 15 34 77 78      (OK)
>
>> x <- c(12,34,15,77,78,22)
>> x[rank(x)]
> [1] 12 77 34 78 22 15   (?)
>
>> x <- c(12,34,77,15,78)
>> x[rank(x)]
> [1] 12 77 15 34 78      (?)
>
> Please any feedback ? Thanks.
>
> BR,
>
> Giorgio Garziano
>
>
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help