order(..., na.last = TRUE, decreasing = FALSE) sort.list(x, partial = NULL, na.last = TRUE, decreasing = FALSE, method = c("shell", "quick", "radix"))
... | any number of vectors. The vectors can be a mix of numeric, character, and complex. All vectors should have the same length. Missing values (NAs) are allowed. |
x | a vector. Missing values (NAs) are allowed. For numeric vectors, infinite values are also allowed. |
na.last | a logical value. If TRUE (the default), missing values (NAs) are placed last. If FALSE, NAs are placed first. If na.last=NA, NAs are discarded. |
decreasing | a logical value. If TRUE, the elements have a descending sort order. If FALSE (the default), the elements have an ascending order. |
partial | a vector of indices (in ascending order) into data for partial sorting. |
method | by default, the vector is sorted using a stable sort algorithm. if method = "quick" is specified, an unstable (and faster) sort algorithm is used. Specifying any other method is treated like the default. In particular, the "shell" and "radix" methods are present only for R compatibility and do not imply using shell sort or radix sort. |
x <- c(4, NA, -Inf, 3, 5, 7) # create sample object # order says that the smallest element in x (-Inf) is found in # position 3, the next largest in position 4, etc, and NA is # considered the largest value. order(x, na.last=TRUE) # [1] 3 4 1 5 6 2 sort.list(x, na.last=TRUE) # same as order result# Here the NA value is removed. order(x, na.last=NA) # [1] 3 4 1 5 6 sort.list(x, na.last=NA) # same as order result
x[order(x, decreasing=TRUE)] # x sorted in decreasing order
x100 <- sample(1:100, 100) # 1 to 100 permuted sl <- sort.list(x100, partial=c(1:3, 98:100)) sl[c(1:3, 98:100)] # indices of 3 smallest and 3 largest values of x100
x100[sl[c(1:3, 98:100)]] # [1] 1 2 3 98 99 100
# Use order to sort a data frame: xdf <- data.frame(Age=sample(18:50, 20, rep=TRUE), Gender=sample(c("F", "M"), 20, rep=TRUE), Height=sample(58:74, 20, rep=TRUE)) oo <- order(xdf$Gender, xdf$Age) xdf[oo, ] # sorted by Gender, then Age