\HeaderA{reorder.factor}{Reorder Levels of a Factor}{reorder.factor}
\aliasA{reorder}{reorder.factor}{reorder}
\methaliasA{reorder.character}{reorder.factor}{reorder.character}
\keyword{utilities}{reorder.factor}
\begin{Description}\relax
\code{reorder} is a generic function.  Its \code{"factor"} method
reorders the levels of a factor depending on values of a second
variable, usually numeric.  The \code{"character"} method is a
convenient alias.
\end{Description}
\begin{Usage}
\begin{verbatim}
reorder(x, ...)

## S3 method for class 'factor':
reorder(x, X, FUN = mean, ...,
        order = is.ordered(x))

## S3 method for class 'character':
reorder(x, X, FUN = mean, ...,
        order = is.ordered(x))
\end{verbatim}
\end{Usage}
\begin{Arguments}
\begin{ldescription}
\item[\code{x}] a character vector or factor (possibly ordered) or whose levels will
be reordered.

\item[\code{X}] a vector of the same length as \code{x}, whose subset
of values for each unique level of \code{x} determines the
eventual order of that level.

\item[\code{FUN}] a function whose first argument is a vector and
returns a scalar, to be applied to each subset of \code{X}
determined by the levels of \code{x}.

\item[\code{...}] optional: extra arguments supplied to \code{FUN}
\item[\code{order}] logical, whether return value will be an ordered factor
rather than a factor.

\end{ldescription}
\end{Arguments}
\begin{Value}
A factor or an ordered factor (depending on the value of
\code{order}), with the order of the levels determined by
\code{FUN} applied to \code{X} grouped by \code{x}.  The
levels are ordered such that the values returned by \code{FUN}
are in increasing order.

Additionally, the values of \code{FUN} applied to the subsets of
\code{X} (in the original order of the levels of \code{x}) is returned
as the \code{"scores"} attribute.
\end{Value}
\begin{Author}\relax
Deepayan Sarkar \email{deepayan.sarkar@r-project.org}
\end{Author}
\begin{SeeAlso}\relax
\code{\LinkA{reorder.dendrogram}{reorder.dendrogram}}, \code{\LinkA{levels}{levels}},
\code{\LinkA{relevel}{relevel}}.
\end{SeeAlso}
\begin{Examples}
\begin{ExampleCode}
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")
\end{ExampleCode}
\end{Examples}

