Reorder the Levels of a Factor

USAGE:

reorder.factor(Factor, X, Function = mean, ...) 

ARGUMENTS:

Factor
a factor.
X
a numeric vector of the same length as Factor.
Function
a summary function that is applied to the groups of X (as determined by Factor ). The values of this summary function, in ascending order, are used to rearrange the levels of Factor.
...
any other arguments to be passed into Function.

VALUE:

an ordered factor like Factor but with a rearranged levels attribute. The reordered factor is often useful for making plots more meaningful.

SEE ALSO:

, .

EXAMPLES:

# make the shorter singers first 
reorder.factor(singer$voice.part, singer$height) 
# make the taller singers first 
reorder.factor(singer$voice.part, singer$height, function(x) -mean(x)) 
  # or 
reorder.factor(singer$voice.part, -singer$height) 
# the definition of the function is relatively simple 
reorder.factor <- function(Factor, X, Function = mean, ...) 
        ordered(Factor, 
                levels(Factor)[order(tapply(X, Factor, Function, ...))])