reorder.default {stats} | R Documentation |
Reorder Levels of a Factor
Description
reorder
is a generic function. The "default"
method
treats its first argument as a categorical variable, and reorders its
levels based on the values of a second variable, usually numeric.
Usage
reorder(x, ...)
## Default S3 method:
reorder(x, X, FUN = mean, ...,
order = is.ordered(x), decreasing = FALSE)
Arguments
x |
an atomic vector, usually a |
X |
a vector of the same length as |
FUN |
a |
... |
optional: extra arguments supplied to |
order |
logical, whether return value will be an ordered factor rather than a factor. |
decreasing |
logical, whether the levels will be ordered in increasing or decreasing order. |
Details
This, as relevel()
, is a special case of simply calling
factor(x, levels = levels(x)[....])
.
Value
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 x
. By default, the
levels are ordered such that the values returned by FUN
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
as the "scores"
attribute.
Author(s)
Deepayan Sarkar deepayan.sarkar@r-project.org
See Also
reorder.dendrogram
, levels
,
relevel
.
Examples
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")
bymedianR <- with(InsectSprays, reorder(spray, count, median, decreasing=TRUE))
stopifnot(exprs = {
identical(attr(bymedian, "scores") -> sc,
attr(bymedianR,"scores"))
identical(nms <- names(sc), LETTERS[1:6])
identical(levels(bymedian ), nms[isc <- order(sc)])
identical(levels(bymedianR), nms[rev(isc)])
})