Changing the order of levels of a factor

Problem

You want to change the order in which the levels of a factor appear.

Solution

Factors in R come in two varieties: ordered and unordered, e.g., {small, medium, large} and {pen, brush, pencil}. For most analyses, it will not matter whether a factor is ordered or unordered. If the factor is ordered, then the specific order of the levels matters (small < medium < large). If the factor is unordered, then the levels will still appear in some order, but the specific order of the levels matters only for convenience (pen, pencil, brush) – it will determine, for example, how output will be printed, or the arrangement of items on a graph.

One way to change the level order is to use factor() on the factor and specify the order directly. In this example, the function ordered() could be used instead of factor().

Here’s the sample data:

  1. # Create a factor with the wrong order of levels
  2. sizes <- factor(c("small", "large", "large", "small", "medium"))
  3. sizes
  4. #> [1] small large large small medium
  5. #> Levels: large medium small

The levels can be specified explicitly:

  1. sizes <- factor(sizes, levels = c("small", "medium", "large"))
  2. sizes
  3. #> [1] small large large small medium
  4. #> Levels: small medium large

We can do the same with an ordered factor:

  1. sizes <- ordered(c("small", "large", "large", "small", "medium"))
  2. sizes <- ordered(sizes, levels = c("small", "medium", "large"))
  3. sizes
  4. #> [1] small large large small medium
  5. #> Levels: small < medium < large

Another way to change the order is to use relevel() to make a particular level first in the list. (This will not work for ordered factors.)

  1. # Create a factor with the wrong order of levels
  2. sizes <- factor(c("small", "large", "large", "small", "medium"))
  3. sizes
  4. #> [1] small large large small medium
  5. #> Levels: large medium small
  6. # Make medium first
  7. sizes <- relevel(sizes, "medium")
  8. sizes
  9. #> [1] small large large small medium
  10. #> Levels: medium large small
  11. # Make small first
  12. sizes <- relevel(sizes, "small")
  13. sizes
  14. #> [1] small large large small medium
  15. #> Levels: small medium large

You can also specify the proper order when the factor is created.

  1. sizes <- factor(c("small", "large", "large", "small", "medium"),
  2. levels = c("small", "medium", "large"))
  3. sizes
  4. #> [1] small large large small medium
  5. #> Levels: small medium large

To reverse the order of levels in a factor:

  1. # Create a factor with the wrong order of levels
  2. sizes <- factor(c("small", "large", "large", "small", "medium"))
  3. sizes
  4. #> [1] small large large small medium
  5. #> Levels: large medium small
  6. sizes <- factor(sizes, levels=rev(levels(sizes)))
  7. sizes
  8. #> [1] small large large small medium
  9. #> Levels: small medium large