Use purrr map2, pmap and reduce for Elementwise Iteration in R
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement four R functions that combine aligned inputs elementwise with `purrr` helpers, either mapping to a vector or reducing to a scalar. Assume `purrr` is installed.
- `map2_ratio(num, den)`: using `purrr::map2`, return a numeric vector of `num[i] / den[i]`, with `NA_real_` where `den[i] == 0`.
- `reduce_weighted_sum(values, weights)`: multiply elementwise with `map2`, then combine with `purrr::reduce` and `` `+` ``. Return a numeric scalar (`0` for empty inputs).
- `pmap_linear(df)`: `df` has numeric columns `a`, `b` and `x`. Using `purrr::pmap`, return a numeric vector of `a * x + b` per row, of length `nrow(df)`.
- `pmap_label(df)`: `df` has a character column `name` and a numeric column `count`. Using `purrr::pmap`, return a character vector of `paste0(name, ": ", count)` per row, of length `nrow(df)`.
- For inputs of unequal length (lengths greater than 1), do not pre-check; let `map2` raise its own error.
For example:
```r
map2_ratio(c(10, 6, 4), c(2, 0, 8))
# c(5, NA, 0.5)
reduce_weighted_sum(c(1, 2, 3), c(0.5, 0.5, 1))
# 4.5
pmap_linear(data.frame(a = c(2, 3), b = c(1, 0), x = c(4, 5)))
# c(9, 15)
pmap_label(data.frame(name = c("x", "y"), count = c(3, 7)))
# c("x: 3", "y: 7")
```
```hint Return shapes
Check what plain `map2()` and `pmap()` return, compare it with the vector types the spec asks for, and run your fold on a zero-length input.
```
### What a Strong Answer Covers
- `map2` for two parallel vectors and `pmap` for row-wise calls over a data frame, with outputs of the stated type and length.
- The zero-denominator rule, and a stated choice for missing denominators.
- A fold that returns 0 on empty input.
- Behaviour on unequal lengths left to `map2`'s own error, and how length-1 inputs are recycled.
### Follow-up Questions
- Why prefer the typed variants like `map2_dbl` over `map2`?
- How does `reduce` behave on empty input, and how do you guarantee 0?
Overview: Implement four small R functions with purrr: an elementwise ratio with map2, a weighted sum folded with reduce, and two row-wise calculations over a data frame with pmap. Tests typed map variants, empty-input folds, zero denominators and length recycling rules.