forcats::fct_relevel()
   get_help() docs


Description

The fct_relevel() function is part of the {forcats} package, which is part of the {tidyverse}.

We use the fct_relevel() function to change the order of categories (levels) in a factor variable based on your custom ordering, using a variety of flexible syntaxes.

Changing the order of factor levels is commonly performed to change axis order of a factor variable when using plotting with the {ggplot2} library.

To use this function, you need to either first load the {forcats} library, or always use the function with forcats::fct_relevel() notation.

# Load the library
library(forcats)
# Or, load the full tidyverse:
library(tidyverse)

# Or, use :: notation
forcats::fct_relevel()

Conceptual Usage

See examples for what sorts of additional arguments one can provide.

fct_relevel(factor variable to relevel, 
            ..additional arguments for how to relevel..)

Examples

The examples below use a modified version of the msleep dataset called msleep_fctvore. Learn more about this dataset with get_help("msleep").

In this modified dataset, the vore column has been coerced into a factor type (instead of character), and all NA values have been removed from that column. (Notice below, the vore column is annotated <fct> since it’s a factor).

# Show the modified msleep dataset, msleep_fctvore, with head()
head(msleep_fctvore)
## # A tibble: 6 × 11
##   name  genus vore  order conservation sleep_total sleep_rem sleep_cycle awake  brainwt  bodywt
##   <chr> <chr> <fct> <chr> <chr>              <dbl>     <dbl>       <dbl> <dbl>    <dbl>   <dbl>
## 1 Owl … Aotus omni  Prim… <NA>                17         1.8      NA       7    0.0155    0.48 
## 2 Moun… Aplo… herbi Rode… nt                  14.4       2.4      NA       9.6 NA         1.35 
## 3 Grea… Blar… omni  Sori… lc                  14.9       2.3       0.133   9.1  0.00029   0.019
## 4 Cow   Bos   herbi Arti… domesticated         4         0.7       0.667  20    0.423   600    
## 5 Thre… Brad… herbi Pilo… <NA>                14.4       2.2       0.767   9.6 NA         3.85 
## 6 Nort… Call… carni Carn… vu                   8.7       1.4       0.383  15.3 NA        20.5

# Show the default order (alphabetical!) of the factor vore column.
# All examples below will use the function fct_relevel() to manipulate this order:
levels(msleep_fctvore$vore)
## [1] "carni"   "herbi"   "insecti" "omni"


# Re-write the `vore` column, releveled to make "omni" come first
msleep_fctvore %>%
  mutate(vore = fct_relevel(vore, "omni")) -> msleep_fctvore_ex1

# Show new levels to confirm "omni" is now first
levels(msleep_fctvore_ex1$vore)
## [1] "omni"    "carni"   "herbi"   "insecti"


# Re-write the `vore` column, releveled as: "omni", "herbi", "carni", "insecti"
# You can freely list out the additional arguments inside `fct_relevel()`
msleep_fctvore %>%
  mutate(vore = fct_relevel(vore, 
                            "omni", "herbi", "carni", "insecti")) -> msleep_fctvore_ex2

# Show new levels to confirm new order
levels(msleep_fctvore_ex2$vore)
## [1] "omni"    "herbi"   "carni"   "insecti"


# Re-write the `vore` column, releveled to make "insect" second, aka:
# "insecti" should come _after_ the first (1) level. (Note: there is no alternative `before` argument.)
# This fct_relevel approach is helpful when you want to move one level without listing all the levels out
msleep_fctvore %>%
  mutate(vore = fct_relevel(vore, "insecti", after = 1)) -> msleep_fctvore_ex3

# Show new levels to confirm new order
levels(msleep_fctvore_ex3$vore)
## [1] "carni"   "insecti" "herbi"   "omni"


# Re-write the `vore` column, releveled to make "insect" LAST, using `Inf` ("infinity")
# "insecti" should come _after_ the first level
# This fct_relevel approach is helpful when you want to move one level without listing all the levels out

msleep_fctvore %>%
  mutate(vore = fct_relevel(vore, "insecti", after = Inf)) -> msleep_fctvore_ex4

# Show new levels to confirm new order
levels(msleep_fctvore_ex4$vore)
## [1] "carni"   "herbi"   "omni"    "insecti"


# Without re-writing the column, reorder the levels for _plotting purposes only_
# Provide fct_relevel(VARIABLE) to ggplot2::aes() to order in your plot
# This affects the x-axis labeling, so it is best practice to clean up with `labs()`
ggplot(msleep_fctvore) +
                            # Order we want `vore` to appear in
  aes(x = fct_relevel(vore, "insecti", "carni", "omni", "herbi"), 
      y = awake) + 
  geom_boxplot() + 
  labs(x = "vore")