Description

lock_factors(df, cols = NULL, rev = FALSE)

Arguments

df

A data.frame object.

cols

A character or character vector of the column names to apply the factor leveling to. Defaults to NULL in which case all character or factor type variables will be re-leveled.

rev

Reverse the factor level? Defaults to FALSE

Value

The function returns a data frame.

Examples

library(ggplot2)
library(dplyr)
#> 
#> Attaching package: ‘dplyr’
#> The following objects are masked from ‘package:stats’:
#> 
#>     filter, lag
#> The following objects are masked from ‘package:base’:
#> 
#>     intersect, setdiff, setequal, union

# By default, bar charts made with {ggplot2} follow alphabetical ordering:

mpg |>
  count(manufacturer) |>
  ggplot() +
  geom_col(aes(x = n, y = manufacturer))


# If you want to sort the bars based on n,
# you have to reorder the **factor levels**:

mpg |>
  count(manufacturer) |>
  ggplot() +
  geom_col(aes(x = n, y = reorder(manufacturer, n)))


# {factorlock} allows you to "lock" the factor ordering
# to that of the row ordering in the data frame:

mpg |>
  count(manufacturer) |>
  arrange(n) |>
  factorlock::lock_factors() |>
  ggplot() +
  geom_col(aes(x = n, y = manufacturer))


# By default all character or factor type variables are "locked,"
# but you can also specify which variables you want to "lock" while
# leaving the others alone:

mpg |>
  count(manufacturer) |>
  arrange(n) |>
  factorlock::lock_factors("manufacturer") |>
  ggplot() +
  geom_col(aes(x = n, y = manufacturer))


# You can also get a reverse factor ordering with `rev = TRUE`:

mpg |>
  count(manufacturer) |>
  arrange(n) |>
  factorlock::lock_factors(rev = TRUE) |>
  ggplot() +
  geom_col(aes(x = n, y = manufacturer))