Reorder Levels of a Factor
reorder is a generic function. The
treats its first argument as a categorical variable, and reorders its
levels based on the values of a second variable, usually numeric.
# S3 method for default reorder(x, X, FUN = mean, …, order = is.ordered(x))
an atomic vector, usually a
factor(possibly ordered). The vector is treated as a categorical variable whose levels will be reordered. If
xis not a factor, its unique values will be used as the implicit levels.
a vector of the same length as
x, whose subset of values for each unique level of
xdetermines the eventual order of that level.
functionwhose first argument is a vector and returns a scalar, to be applied to each subset of
Xdetermined by the levels of
optional: extra arguments supplied to
logical, whether return value will be an ordered factor rather than a factor.
A factor or an ordered factor (depending on the value of
order), with the order of the levels determined by
FUN applied to
X grouped by
levels are ordered such that the values returned by
are in increasing order. Empty levels will be dropped.
Additionally, the values of
FUN applied to the subsets of
X (in the original order of the levels of
x) is returned
require(graphics) bymedian <- with(InsectSprays, reorder(spray, count, median)) boxplot(count ~ bymedian, data = InsectSprays, xlab = "Type of spray", ylab = "Insect count", main = "InsectSprays data", varwidth = TRUE, col = "lightgray")