14

How do I write a main function flexible enough to pass extra arguments along to multiple functions? Simple attempts have failed:

> mainF <- function(f1,f2,...) {
+     f2( X=f1(...), ... )
+ }
> mainF(function(x) x, function(X, y) X*y, x=5, y=3)
Error in f2(X = f1(...), ...) : unused argument (x = 5)

I can see how this might be possible by examining formals and matching call arguments in the ellipsis to the formals of each function. Is there a better way, though?

Ari B. Friedman
  • 71,271
  • 35
  • 175
  • 235
  • 3
    you can pass a list to one of the subfunctions, ie ` mainF <- function(f1,f2,..., args.f2 = list())`. – baptiste May 27 '13 at 14:28
  • Other than the idiom @baptiste mentions (which is often used in the R sources), you are into argument processing territory. You can grab `...`, get the argument names of `f1` and `f2` via `formals()`, then process the grabbed `...` list to extract arguments for each function. What happens however when `f1` and `f2` have the same named arguments? This is why baptiste's idea is nice a simple; you just need `do.call(f2, args.f2)` to call `f2` with the correct set of arguments as specified by the user. – Gavin Simpson May 27 '13 at 14:42
  • That's a great idiom. I've probably seen it a million times in base R but it didn't occur to me to do it that way for some reason. @baptiste post as an answer? – Ari B. Friedman May 27 '13 at 15:04
  • You might also wanna check [this question by me](http://stackoverflow.com/q/4124900/289572) – Henrik May 27 '13 at 15:14
  • @Henrik That's great. Voting to close as duplicate. – Ari B. Friedman May 27 '13 at 17:41

1 Answers1

5

You can pass a list to one of the subfunctions, ie

mainF <- function(f1, f2, ..., args.f2 = list()) {
     do.call(f2, c(X=f1(...), args.f2))
}

mainF(function(x) x, function(X, y) X*y, x=5, args.f2 = list(y=3))

(untested, but you got the gist)

baptiste
  • 75,767
  • 19
  • 198
  • 294