[R] I don't understand the 'order' function

Ted Harding Ted.Harding at wlandres.net
Tue Apr 16 20:12:24 CEST 2013


[See in-line below[

On 16-Apr-2013 17:51:41 Julio Sergio wrote:
> I thought I've understood the 'order' function, using simple examples like:
> 
>    order(c(5,4,-2))
>    [1] 3 2 1
> 
> However, I arrived to the following example:
> 
>    order(c(2465, 2255, 2085, 1545, 1335, 1210, 920, 210, 210, 505, 1045)) 
>    [1]  8  9 10  7 11  6  5  4  3  2  1
> 
> and I was completely perplexed!
> Shouldn't the output vector be  11 10 9 8 7 6 4 1 2 3 5 ?
> Do I have a damaged version of R?

I think the simplest explanation can be given as:

S <- c(2465, 2255, 2085, 1545, 1335, 1210, 920, 210, 210, 505, 1045)
cbind(Index=1:length(S), S, Order=order(S), Sort=sort(S))
      Index    S Order Sort
 [1,]     1 2465     8  210
 [2,]     2 2255     9  210
 [3,]     3 2085    10  505
 [4,]     4 1545     7  920
 [5,]     5 1335    11 1045
 [6,]     6 1210     6 1210
 [7,]     7  920     5 1335
 [8,]     8  210     4 1545
 [9,]     9  210     3 2085
[10,]    10  505     2 2255
[11,]    11 1045     1 2465

showing that the value of 'order' for any one of the numbers
is the Index (position) of that number in the original series,
placed in the position that number occupies in the sorted series.
(With a tie for S[8] = S[9] = 210).

For example: which one of S occurs in 5th position in the sorted
series? It is the 11th of S (1045).

> I became still more astonished when I used the sort function and got the 
> right answer: 
> 
> sort(c(2465, 2255, 2085, 1545, 1335, 1210,  920,  210,  210,  505, 1045))
> [1]  210  210  505  920 1045 1210 1335 1545 2085 2255 2465
> since 'sort' documentation claims to be using 'order' to establish the right 
> order.

Indeed, once you have order(S), you know which element of S to put in
each position of the sorted order:

  S[order(S)]
  [1]  210  210  505  920 1045 1210 1335 1545 2085 2255 2465

Does this help to explain it?
Ted.

> Please help me to understand all this!
> 
>   Thanks,
> 
>   -Sergio.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

-------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at wlandres.net>
Date: 16-Apr-2013  Time: 19:12:21
This message was sent by XFMail



More information about the R-help mailing list