Graphics Reference
In-Depth Information
Changing the Order of Factor Levels Based on Data
Values
Problem
You want to change the order of levels in a factor based on values in the data.
Solution
Use reorder() with the factor that has levels to reorder, the values to base the reordering on,
and a function that aggregates the values:
# Make a copy since we'll modify it
iss <- InsectSprays
iss$spray
[ 1 ] A A A A A A A A A A A A B B B B B B B B B B B B C C C C C C C C C C C C D D
[ 39 ] D D D D D D D D D D E E E E E E E E E E E E F F F F F F F F F F F F
Levels: A B C D E F
iss$spray <- reorder(iss$spray, iss$count, FUN = mean)
iss$spray
[ 1 ] A A A A A A A A A A A A B B B B B B B B B B B B C C C C C C C C C C C C D D
[ 39 ] D D D D D D D D D D E E E E E E E E E E E E F F F F F F F F F F F F
attr(, "scores" )
A B C D E F
14.500000 15.333333 2.083333 4.916667 3.500000 16.666667
Levels: C E D A B F
Notice that the original levels were ABCDEF , while the reordered levels are CEDABF . The new or-
der is determined by splitting iss$count into pieces according to the values in iss$spray , and
then taking the mean of each group.
Discussion
The usefulness of reorder() might not be obvious from just looking at the raw output. Fig-
ure 15-1 shows three graphs made with reorder() . In these graphs, the order in which the
items appear is determined by their values.
Search WWH ::




Custom Search