Reorder, lump, collapse and count factor levels in R with forcats
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Using `forcats`, implement four factor helpers in R: reorder levels by a statistic, lump rare levels, collapse levels, and tabulate level frequencies.
- `reorder_by_median(df, cat_col, num_col)` takes the column names as length-1 strings. It returns `df[[cat_col]]` as a factor, aligned with the rows of `df`, whose levels are sorted ascending by the median of `num_col` within each level. Use `fct_reorder(.fun = median)`.
- `lump_rare(x, n)` keeps the `n` most frequent levels and lumps the rest into one level with `fct_lump_n(other_level = "Other")`.
- `collapse_levels(x, groups)` takes `groups` as a named list that maps each new level to a vector of existing levels. Use `fct_collapse`; levels not mentioned in `groups` stay unchanged.
- `level_freq_table(x)` returns a data.frame with columns `level` (character) and `count` (integer), sorted by `count` descending and then `level` ascending, with row names 1 to k.
Examples:
```r
df <- data.frame(g = c("a", "b", "a", "b"), v = c(1, 10, 3, 20))
reorder_by_median(df, "g", "v")
# factor values a b a b with levels c("a", "b") (median a = 2 < b = 15)
level_freq_table(c("x", "y", "x", "z", "z", "z"))
# level count
# 1 z 3
# 2 x 2
# 3 y 1
```
```hint A list as arguments
`fct_collapse` expects each new level as its own named argument, but `groups` arrives as a single list at run time. Look for a way to splice a list into a function call.
```
```hint Deterministic output
For the frequency table, check what order two levels with the same count end up in, and what the row names look like after you reorder the rows.
```
### Clarifying Questions to Ask
- Should levels with a zero count (unused levels of a factor input) appear in the frequency table?
- If several levels tie at the `n`th place, should `lump_rare` keep all of them or exactly `n`?
- How should missing values in `num_col` or in `x` be treated?
- Should "level ascending" follow the current locale's collation or plain C-locale order?
### What a Strong Answer Covers
- Picks the matching `forcats` verb for each helper and keeps every returned factor aligned with the input rows
- Splices the run-time `groups` list into `fct_collapse` correctly
- Builds the frequency table with the right column types, the two-key sort and reset row names
- Explains how ties behave in `fct_lump_n` and `fct_reorder`, and how missing values are handled
- Traces the given examples
### Follow-up Questions
- How does `fct_reorder` handle NA values in `num_col`?
- When would you prefer `fct_lump_prop` or `fct_lump_min` over `fct_lump_n`?
- Which `forcats` function orders levels by frequency for a bar chart, and how does that relate to `level_freq_table`?
Overview: Implement four R helpers with forcats that reorder factor levels by a per-level median, lump rare levels into an Other level, collapse levels from a named list, and build a sorted frequency table. It tests factor semantics, tie handling and keeping results aligned with the input rows.