order(..., na.last=T)
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.
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