Implement R helper functions with lapply, vapply and purrr::map
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement four helpers in R over lists and vectors using functional style (`lapply()`, `sapply()`, or `purrr` map functions). Each returns a specific shape.
- `element_lengths(lst)`: a named integer vector of `length()` per element, with names from `names(lst)` (no names if the list is unnamed) and the order preserved.
- `column_stats(df)`: for a numeric `data.frame`, return a `data.frame` with columns `column`, `mean` and `sd` (one row per input column, computed with `na.rm = TRUE`), sorted ascending by `column`.
- `scale_each(lst)`: a list of the same length and names, with each numeric vector divided by its own `sum(x)`.
- `apply_funcs(x, funcs)`: a named numeric vector where element `i` is `funcs[[i]](x)`, with names from `names(funcs)`.
Examples:
```r
element_lengths(list(a = 1:3, b = 1:5))
# a b
# 3 5
apply_funcs(c(1, 2, 3, 4), list(mean = mean, max = max))
# mean max
# 2.5 4.0
column_stats(data.frame(b = c(1, 2, 3), a = c(4, NA, 8)))
# column mean sd
# 1 a 6 2.828427
# 2 b 2 1.000000
scale_each(list(x = c(1, 3), y = c(2, 2, 4)))
# $x
# [1] 0.25 0.75
#
# $y
# [1] 0.25 0.25 0.50
```
```hint Shape stability
Check what `sapply()` returns for an empty list, or when one result has a different length. Some apply-family functions let you declare the result type up front.
```
### What a Strong Answer Covers
- Picks the apply or map variant that gives each required shape: an integer vector, a data.frame, a list, a double vector.
- Keeps names and order from the input without manual bookkeeping.
- Handles missing values in `column_stats` and produces a clean, sorted data.frame with reset row names.
- Explains why a type-stable variant is safer than `sapply()` for empty or irregular input.
### Follow-up Questions
- When would you reach for `vapply()` over `sapply()`?
- How would `column_stats` change for a mix of numeric and non-numeric columns?
- What should `scale_each` do with a vector that sums to zero or contains `NA`?
Overview: Write four small R helpers with lapply, vapply or purrr map functions: element lengths, per-column mean and sd, per-vector scaling and applying a list of functions. It tests choosing the apply variant that returns the right shape, keeping names and order, and handling missing values and empty input.