Summarize sales by region and pick the top product per region with dplyr in R
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement two pure helpers (no printing or side effects) in `/app/solution.R` using `dplyr` and the pipe. Input `df` has columns `region` (character), `product` (character), `quantity` (numeric) and `price` (numeric).
- `sales_summary(df, min_qty)`: keep `quantity >= min_qty`, add `revenue = quantity * price`, and group by `region`. It returns `region`, `total_revenue` (sum, numeric), `avg_quantity` (mean, numeric) and `n_orders` (integer row count), sorted by `region` ascending.
- `top_product_per_region(df)`: sum revenue by `region` and `product`, then keep each region's highest-revenue product (ties: `product` ascending). It returns `region`, `product` and `product_revenue`, one row per region, sorted by `region` ascending.
Example:
```r
df <- data.frame(
region = c("East", "East", "West", "West"),
product = c("A", "B", "A", "A"),
quantity = c(10, 5, 8, 2),
price = c(2, 4, 3, 3)
)
sales_summary(df, min_qty = 5)
# region total_revenue avg_quantity n_orders
# East 40 7.5 2
# West 24 8 1
top_product_per_region(df)
# region product product_revenue
# East A 20
# West A 30
```
```hint Breaking the tie
Taking the first row of each group is only deterministic once the row order inside every group is fully specified. Check what your chosen verb does when two products have the same revenue.
```
### Constraints & Assumptions
- A tibble is an acceptable return type.
- `df` is non-empty and matches the schema.
### What a Strong Answer Covers
- Applying the `min_qty` filter before computing revenue and the summaries
- Correct aggregates with the required types, including an integer order count
- Exactly one row per region from `top_product_per_region`, with a deterministic ascending tie break on `product`
- Ungrouped output sorted by `region`, with the input left unchanged and nothing printed
### Follow-up Questions
- How would you handle a `region` with no rows meeting `min_qty`?
- Why prefer `slice_max()` over `arrange()` plus `slice(1)` for the top product, and what does it do with ties?
- How would the functions change if `quantity` or `price` could contain `NA`?
Overview: Write two pure dplyr helpers in R: one filters orders by a minimum quantity and summarizes revenue, average quantity and order count by region, and one returns the highest-revenue product in each region with a tie rule. It tests filter, mutate, group_by, summarise and deterministic top-row selection.