typestar

forcats in R

Factors that behave: reordered by another variable, or lumped by frequency.

library(forcats)
library(dplyr)

runs <- tibble(
  lang = factor(c("r", "python", "sql", "css", "r", "python", "python")),
  tpm = c(88, 104, 79, 70, 96, 99, 101)
)

print(levels(runs$lang))
print(levels(fct_reorder(runs$lang, runs$tpm, .fun = mean)))
print(table(fct_lump_n(runs$lang, n = 2)))
print(levels(fct_relevel(runs$lang, "sql")))
print(levels(fct_infreq(runs$lang)))
print(fct_count(runs$lang, sort = TRUE))

How it works

  1. fct_reorder sorts the levels by a summary of another column.
  2. fct_lump_n keeps the top n and bundles the rest.
  3. fct_relevel puts a chosen level first, for a model baseline.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
413
Tokens
145
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 83 seconds.

Type this snippet

Step 2 of 2 in Dates & factors, step 9 of 10 in Functional & text tools.

← Previous Next →