Compute Per-Category Running Counts and Grouped Cumulative Sums in R
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement two running-total helpers in R, `cumulative_category_count(x)` and `group_cumsum(df, group_col, value_col, order_col)`. Both preserve the original input ordering. Base R (`ave`, `split`, `order`) and `dplyr` are both acceptable.
- `cumulative_category_count(x)`: `x` is a character or factor vector. Return an integer vector of the same length where element `i` counts the occurrences of `x[i]` up to and including position `i`.
- `group_cumsum`: return a data.frame with all original rows (in the original order, not sorted) and all original columns, plus a numeric column `cum_sum`.
- `cum_sum` is the cumulative sum of `value_col` within each `group_col` group, accumulated in ascending `order_col` order.
- `group_col`, `value_col` and `order_col` are length-1 character column names.
For example:
```r
cumulative_category_count(c("a", "b", "a", "a", "b"))
# [1] 1 1 2 3 2
df <- data.frame(g = c("x", "y", "x", "x"),
v = c(10, 5, 20, 3),
t = c(1, 1, 2, 3))
group_cumsum(df, "g", "v", "t")
# g v t cum_sum
# 1 x 10 1 10
# 2 y 5 1 5
# 3 x 20 2 30
# 4 x 3 3 33
```
```hint Group-wise helpers
Look at what base R's `ave()` returns and in which positions, and record each row's position before you sort anything.
```
### What a Strong Answer Covers
- A running occurrence count that restarts for each category and comes back as an integer vector.
- Accumulation in ascending `order_col` within each group, with every result written back to its original row.
- Output that keeps all rows and columns in input order and adds a numeric `cum_sum`.
- A stated rule for ties in `order_col` and for missing values in the grouping, value and order columns.
### Follow-up Questions
- How would you break ties when two rows share the same `order_col` value within a group?
- How would you generalize `group_cumsum` to multiple grouping columns?
Overview: Write two R helpers: a running occurrence count for each category in a vector, and a cumulative sum within groups that accumulates in the order of a chosen column while returning rows in their original order. Tests ave(), order(), dplyr grouping, tie rules and missing-value handling.