2

I have a function f1 which perform some task. Let us say, it performs the following task:

f1 = function(a=1,b=1,c=2){
  res = (a+b)*c
  return(res)
}

Now, this function is called through another function, f2. This function can take the dynamic number of arguments, create all possible combinations and feed the values to function f1 as follows:

f2 = function(...){
  arglist = list(...)
  df = expand.grid(arglist) # Create all possible combinations of the given argument list.
  out = apply(df,1,function(x) f1(x))
  res = unlist(out)
  return(res)
}

Now, a user can provide value for any number of arguments of f1 in f2 like:

f2(a=10)
# Output: 22

However, if I try any other scenario I do not get desirable results:

f2(c=10)
# f2 Output: 22
# Target Output: 20

f2(a=5, c=c(5,10))
# f2 Output: 
12 12
12 22
# Target Output: 30 60

Any suggestions on how to pass such dynamic arguments to f1 through f2?. I have looked at other questions like 1 and 2 but I do not think that they address this problem.

Rahi
  • 135
  • 1
  • 13

1 Answers1

2

If the change the apply to do.call, it would work as expected. Note that apply with MARGIN = 2, loop over the columns of 'df' individually, whereas the 'f1' needs the values of all those available columns (or else use the default values) to calculate the ((a + b) * c)

f2 <- function(...){
  arglist = list(...)
  df = expand.grid(arglist) 
  do.call(f1, df)
}

and the f1

f1 <- function(a=1,b=1,c=2){
  (a+b)*c
 
}

-testing

> f2(a = 10)
[1] 22
> f2(c = 10)
[1] 20
> f2(a = 5, c= c(5, 10))
[1] 30 60
akrun
  • 874,273
  • 37
  • 540
  • 662