reorder.factor
Reorder Levels of a Factor

Description

Reorder Levels of a Factor

Usage

reorder(x, ...)
## Default S3 method:
reorder(x, X, FUN = mean, ..., order = is.ordered(x))

Arguments

x the data: a factor whose levels are to be reordered.
X a vector of data to be grouped by the distinct values in x. It must have the same length as x. Used to calculates the scores corresponding with the level of x. Missing values (NAs) are allowed if FUN accepts them.
FUN a function or a character string giving the name of the function to apply to each subset of X.
order a logical value, if TRUE, an ordered factor will be returned.
... optional arguments to be given to each invocation of FUN or other functions.

Details

There is one method, the default, in the core program. It essentially deals with factors; objects of other types are coerced to be factors. The scores of levels(x) are determined by calling tapply(X, x, FUN, ...). That applies FUN to subsets of X grouped by x: FUN(x[x==level]) for each level in levels(x). If there is an unused level in the factor then the score for that level will be NA. NA scores will be placed at the end of the sorted scores.
Value
reorder.default returns a factor with an attribute scores containing the scores.
See Also
ordered, factor,
Examples
with(InsectSprays, reorder(spray, count, median))
dat <- data.frame(
   size = factor(rep(c("Med","Sm","Lg"), c(3,6,2)), levels=c("Sm","Med","Lg")),
   cost = 2 + sin(1:11))
with(dat, reorder(size, cost, max))    # order levels by max(cost)
with(dat, reorder(size, size, length)) # order levels by popularity
Package stats version 6.1.4-13
Package Index