Derive Order Columns From Price and Quantity in R
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `add_order_columns(df)` in `/app/solution.R`. Given a data frame with numeric columns `price` and `quantity`, return it with two derived columns appended.
The function must meet these requirements:
- `total` is `price * quantity` (numeric, vectorized).
- `value_category` is a character column: `"high"` when `total >= 100`, else `"low"`.
- The original columns stay unchanged and in their original order, followed by `total`, then `value_category`.
- The row count does not change: return the same data frame with the two new columns.
- Call `stop()` if the `price` or `quantity` column is missing.
For example:
```r
df <- data.frame(price = c(50, 20), quantity = c(3, 2))
add_order_columns(df)
# price quantity total value_category
# 1 50 3 150 high
# 2 20 2 40 low
```
```hint Vectorize and validate
Arithmetic between two columns in R is already elementwise, so no loop is needed. Check that both columns exist before you use them, and check the type of the new label column when the data frame has zero rows.
```
### Clarifying Questions to Ask
- What should `value_category` be when `price` or `quantity` is `NA`?
- Can the input already contain a column named `total` or `value_category`, and if so, should it be replaced or rejected?
- Will the input always be a base `data.frame`, or can it be a tibble?
### What a Strong Answer Covers
- Validating that both required columns exist and failing with `stop()` and a clear message before any computation.
- Computing `total` with vectorized arithmetic so the row count and row order are unchanged.
- Producing `value_category` as a character vector, with a total of exactly 100 labeled `"high"`.
- Appending the two new columns after the original ones without reordering or changing existing columns.
- Edge cases such as missing values, a zero-row input and a pre-existing `total` column.
### Follow-up Questions
- How would you make the `"high"`/`"low"` threshold configurable?
- How would you write this with `dplyr`?
- How would you extend the label to more than two categories, such as low, medium and high?
- How would you test the function, and which inputs would you include in the tests?
Overview: Write an R function that appends a price times quantity total column and a high or low value category column to a data frame. It tests vectorized arithmetic, input validation with stop(), keeping column order and row count intact, and handling edge cases such as missing values and empty input.