Ordering to Create Sorted Data

DESCRIPTION:
Returns an integer vector containing the permutation that will sort the input into ascending order.

USAGE:
order(..., na.last=T)

REQUIRED ARGUMENTS:
...:
any number of vectors. The vectors may be a mix of numeric, character, and complex. Shorter vectors will be used cyclically.
Missing values (NA) are allowed.

OPTIONAL ARGUMENTS:
na.last=:
a vector of length 1. If TRUE, then missing values (NAs) are placed after all other values. If FALSE, NAs are placed first. When na.last=NA, then NAs are discarded. If na.last is of mode "character" and there are NAs in x, then an error occurs.

VALUE:
integer vector containing the indices of the data elements in ascending order, i.e., the first integer is the subscript of the smallest data element, etc.

DETAILS:
The behavior when missing values are present is controlled by na.last.

Ordering is primarily based on the first argument. Values of the second argument break ties in the first, and so on. All sorting is done in ascending order. By default, the returned value has the same length as the input, but it may be shorter if na.last=NA.

For character vectors, sorting is based on the collating sequence. If complex numbers are ordered, the imaginary part is only used to break ties in the real part.

This function is often used in conjunction with subscripting for sorting several parallel arrays.


SEE ALSO:
rank , rev , sort .

EXAMPLES:
x <- c(8, 4, 2, 6, 3) # create sample object

# order says that the smallest element in x is found in position 3, # the next largest in position 5, etc. order(x)

# ordering by salary within age ord <- order(age, salary) cbind(x[ord], y[ord], z[ord])

# ten largest states by area state.name[rev(order(state.x77[,"Area"]))][1:10]

# sorting a matrix (or data frame) by columns mat # View contents of mat [,1] [,2] [,3] [,4] [,5] [1,] 1 5 6 10 12 [2,] 3 4 9 12 14 [3,] 2 6 7 11 14 [4,] 2 5 8 11 16

mat1 <- mat[order(mat[,1],mat[,2]),1:5] mat1 # View contents of sorted mat1 [,1] [,2] [,3] [,4] [,5] [1,] 1 5 6 10 12 [2,] 2 5 8 11 16 [3,] 2 6 7 11 14 [4,] 3 4 9 12 14