[R] about the function order()

Thomas Lumley tlumley at u.washington.edu
Sat Nov 24 20:27:56 CET 2001


On Sat, 24 Nov 2001, Laurent Gautier wrote:

> Dear all,
>
>
> I have recently experienced something with the function order I cannot
> explain:
>
>
> The help(order) (which I admit having overlooked before) rises even more
> my confusion...
>
> The following lines made me think order() was returning the 'order' each
> value in a vector would take when sorted.
>
> > a <- c(4.1, 3.2, 6.1)
> > order(a)
> [1] 2 1 3
>
> Doing
> > plot(a, order(a)/length(a))
> gave what I expected (an empirical distribution function).
>
>
>
> Hower the following made me think I have been misusing order():
>
> > a <- c(4.1, 3.2, 6.1, 3.1)
> > order(a)
> [1] 4 2 1 3
> >
> > a <- rnorm(50)
> > plot(a, order(a)/50)
>
> My question is, what is really order() doing ?

In a sense it's doing the opposite of what you thought.

The definition of order() is basically that
   a[order(a)]
is in increasing order. This works with your example, where the correct
order is the fourth, second, first, then third element.

You may have been looking for rank(), which returns the rank of the
elements
R> a <- c(4.1, 3.2, 6.1, 3.1)
R> order(a)
[1] 4 2 1 3
R> rank(a)
[1] 3 2 4 1
so rank() tells you what order the numbers are in, order() tells you how
to get them in ascending order.

plot(a, rank(a)/length(a)) will give a graph of the CDF.  To see why
order() is useful, though, try
	plot(a, rank(a)/length(a),type="S")
which gives a mess, because the data are not in increasing order

If you did
   oo<-order(a)
   plot(a[oo],rank(a[oo])/length(a),type="S")
or simply
   oo<-order(a)
   plot(a[oo],(1:length(a))/length(a)),type="S")
you get a line graph of the CDF


	-thomas

Thomas Lumley			Asst. Professor, Biostatistics
tlumley at u.washington.edu	University of Washington, Seattle

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list