## 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:

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

The levels can be specified explicitly:

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

We can do the same with an ordered factor:

``````sizes <- ordered(c("small", "large", "large", "small", "medium"))
sizes <- ordered(sizes, levels = c("small", "medium", "large"))
sizes
#> [1] small  large  large  small  medium
#> 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.)

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

# Make medium first
sizes <- relevel(sizes, "medium")
sizes
#> [1] small  large  large  small  medium
#> Levels: medium large small

# Make small first
sizes <- relevel(sizes, "small")
sizes
#> [1] small  large  large  small  medium
#> Levels: small medium large
``````

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

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

To reverse the order of levels in a factor:

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

sizes <- factor(sizes, levels=rev(levels(sizes)))
sizes
#> [1] small  large  large  small  medium
#> Levels: small medium large
``````