# How to relevel a factor in R

## 2021/06/04

Categories: R Tags: R foot guns

Here is an interesting ‘problem’ I had with R. Suppose we have a factor:

f <- factor(c("a", "a", "b", "b", "b"), levels = c("a", "b"))
f
## [1] a a b b b
## Levels: a b

Suppose I want the levels of f to be reversed, or placed into the order that makes the most sense for my plot.

Here is what not to do: do not mettle with the levels of f directly, this will change the data:

levels(f) <- c("b", "a")
f
## [1] b b a a a
## Levels: b a

Again, this changes the data. Previously, there were 2 a’s. There are now 3. The a’s were mapped to b’s and vice versa.

One solution is to just call factor again.

f <- factor(c("a", "a", "b", "b", "b"), levels = c("a", "b"))
f
## [1] a a b b b
## Levels: a b
f <- factor(f, levels = c("b", "a"))
f
## [1] a a b b b
## Levels: b a

Another solution is to use the forcats library.