Compute grouped summary stats and each group's share of the total with dplyr
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement two grouped-aggregation functions in R using `dplyr`. Column names are passed as length-1 character vectors, and `value_col` names a numeric column.
- `group_stats(df, group_col, value_col)` returns a tibble with one row per distinct value of `group_col`, sorted ascending by it. Its columns, in order, are `<group_col>` (keeping the original column name), `n` (integer count), and numeric `sum`, `mean` and `sd`. `sd` is the sample standard deviation and is `NA` for single-row groups.
- `group_share(df, group_col, value_col)` returns a tibble sorted ascending by `group_col` with columns `<group_col>` and `share`. `share` is the group's sum of `value_col` divided by the grand total of `value_col` across all rows.
Example:
```r
df <- data.frame(g = c("b", "a", "a", "b"), v = c(10, 2, 4, 6))
group_stats(df, "g", "v")
#> # A tibble: 2 x 5
#> g n sum mean sd
#> <chr> <int> <dbl> <dbl> <dbl>
#> 1 a 2 6 3 1.41
#> 2 b 2 16 8 2.83
group_share(df, "g", "v")
#> # A tibble: 2 x 2
#> g share
#> <chr> <dbl>
#> 1 a 0.273
#> 2 b 0.727
```
```hint Column names as strings
The column names arrive as strings. Check how a dplyr verb can refer to a column whose name is stored in a variable.
```
### What a Strong Answer Covers
- How the string arguments become column references inside the dplyr verbs.
- The output column names, order and types, including the integer count and the `NA` standard deviation for single-row groups.
- Where the grand total for `share` is computed, and why the shares add up to 1.
- An explicit ascending sort by the group column.
### Follow-up Questions
- How would you summarise several value columns at once?
- How should `NA` values in `value_col` be handled?
- What happens to `share` when the grand total is zero or the values have mixed signs?
Overview: Write two dplyr functions in R that take column names as strings: one returns the count, sum, mean and sample standard deviation per group, and the other returns each group's share of the grand total. It tests grouped summaries, tidy evaluation with the .data pronoun, and output column contracts.