order

Ordering Permutation

order returns a permutation which rearranges its first
argument into ascending or descending order, breaking ties by further
arguments. sort.list is the same, using only one argument.
See the examples for how to use these functions to sort data frames,
etc.

Usage

Arguments

a sequence of numeric, complex, character or logical
vectors, all of the same length, or a classed R object.

x

an atomic vector.

partial

vector of indices for partial sorting.
(Non-NULL values are not implemented.)

decreasing

logical. Should the sort order be increasing or
decreasing?

na.last

for controlling the treatment of NAs.
If TRUE, missing values in the data are put last; if
FALSE, they are put first; if NA, they are removed
(see Note.)

method

the method to be used: partial matches are allowed. The
default is "shell" except for some special cases: see
Details.

Details

In the case of ties in the first vector, values in the second are used
to break the ties. If the values are still tied, values in the later
arguments are used to break the tie (see the first example).
The sort used is stable (except for method = "quick"),
so any unresolved ties will be left in their original ordering.

Complex values are sorted first by the real part, then the imaginary
part.

The sort order for character vectors will depend on the collating
sequence of the locale in use: see Comparison.

The default method for sort.list is a good compromise. Method
"quick" is only supported for numeric x with
na.last = NA, and is not stable, but will be substantially
faster for long vectors. Method "radix" is only implemented
for integer x with a range of less than 100,000. For such
x it is very fast (and stable), and hence is ideal for sorting
factors---as from R 3.0.0 it is the default method for factors with
less than 100,000 levels.

partial = NULL is supported for compatibility with other
implementations of S, but no other values are accepted and ordering is
always complete.

For a classed R object, the sort order is taken from
xtfrm: as its help page notes, this can be slow unless a
suitable method has been defined or is.numeric(x) is
true. For factors, this sorts on the internal codes, which is
particularly appropriate for ordered factors.

Value

An integer vector unless any of the inputs has $2^31$ or
more elements, when it is a double vector.

Note

sort.list can get called by mistake as a method for
sort with a list argument, and gives a suitable error
message for list x.

There is a historical difference in behaviour for na.last = NA:
sort.list removes the NAs and then computes the order
amongst the remaining elements: order computes the order
amongst the non-NA elements of the original vector. Thus

```
##Note that order() is different from rank(). rank() will return you rank of the elements while order() returns the ranked element's position in the original list:
> a <- c(45,50,10,96)
> order(a)
[1] 3 1 2 4
> rank(a)
[1] 2 3 1 4
```