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
fct_reordersorts the levels by a summary of another column.fct_lump_nkeeps the top n and bundles the rest.fct_relevelputs a chosen level first, for a model baseline.
Keywords and builtins used here
cfactorfct_countfct_infreqfct_lump_nfct_relevelfct_reorderlevelslibraryprinttabletibble
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.
Step 2 of 2 in Dates & factors, step 9 of 10 in Functional & text tools.