Dynamic Function Invocation in R With do.call
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement helpers in `/app/solution.R` that each use `do.call` to invoke a target function (a function object or its name) with a list of arguments.
- `invoke(fn, args)`: `fn` is a function or a character name (resolve it with `match.fun`), and `args` is a possibly-named list. Return `do.call(fn, args)`.
- `apply_stat(stat_name, x, extra = list())`: return the numeric scalar `do.call(stat_name, c(list(x), extra))`, where `extra` is a possibly-empty named list.
- `stack_frames(frames)`: return `do.call(rbind, frames)` with row names reset to `1..N`.
- `build_and_call(fn, positional, named)`: return `do.call(fn, c(positional, named))`, where `positional` is an unnamed list and `named` is a named list.
Examples:
```r
invoke("paste", list("a", "b", sep = "-")) # "a-b"
apply_stat("mean", c(1, 2, 3, 4)) # 2.5
apply_stat("mean", c(1, NA, 3), list(na.rm = TRUE)) # 2
build_and_call("seq", list(1, 10), list(by = 2)) # 1 3 5 7 9
```
```hint Lists become calls
`do.call` treats each list element as one argument and each element name as an argument name. Most of the work is assembling the list so the right elements keep their names.
```
```hint Check the row names
Look at the row names `rbind()` produces when the list of frames is itself named, or when a frame was subset earlier.
```
### What a Strong Answer Covers
- Resolving `fn` from either a function object or a name with `match.fun()`, and what happens when the name does not exist.
- Building argument lists with `c()` so positional elements stay unnamed, named elements keep their names, and `x` comes first in `apply_stat`.
- Resetting row names after `do.call(rbind, frames)` and why one `rbind` call beats binding in a loop.
- How `do.call` matches list elements to formal arguments, plus edge cases such as an empty `extra`, an empty `frames` list and an empty `named` list.
### Follow-up Questions
- Why prefer `do.call` over building a call string and using `eval(parse(...))`?
- How does argument matching work when `named` and `positional` arguments overlap?
- What does `stack_frames(list())` return, and how would you handle that case?
- When would you pass `quote = TRUE` to `do.call`?
Overview: Implement four R helpers that call a function given as an object or a name with a list of arguments, apply a named statistic with extra options, stack a list of data frames and combine positional and named arguments. It tests do.call, match.fun, list construction with names and argument matching rules.