Search code examples
rfunctionargumentsfunction-callforecast

Passing arguments to a function which is called by another function by its name in R


I am using two functions, say Fun1 and Fun2, both are defined in a package, so I cannot change them. Fun1 is calling Fun2 as follows:

Fun1(x=a_number,y=a_string,fn=Fun2,...)

where ... are arguments used by Fun2.

So Fun1 is calling Fun2 by its name. How can I pass parameters to Fun2 without calling parameters names explicitly?

Assume that args is a list of parameters that I want to pass to Fun2. If I want to call only Fun2 it is easy as follows:

do.call(Fun2,args)

But this way does not work if Fun2 is called by Fun1 by its name. The only way is to write parameters explicitly as follows:

Fun1(x=a_number,y=a_string,fn=Fun2,param1=sth,param2=some_other_thing)

But this way doesn't work for me as there are so many parameters of Fun2 (not just 2) and also I don't know which parameters a user wants to change. Maybe the user just wants to change param1, and keep others as default.

By the way, the following does not work since Fun1 does not accept anything but name of function for its 'fn' argument:

Fun1(x=a_number,y=a_string,fn=do.call(Fun2,args))

EDIT 1:

fn=Fun2 (...) doesn't work, because " fn" argument of Fun1 only gets name of the function, nothing else.

EDIT 2:

Actually Fun1 is baggedModel and Fun2 is auto.arima, both of them are in forecast package. Here is an example:

vec.ts=ts(1:27,start=c(2016,1),frequency=12) #time series
num_blocks=3
block_size=24
baggedModel(vec.ts,
         bootstrapped_series = bld.mbb.bootstrap(vec.ts,num_blocks,block_size),
         fn=auto.arima,...)

So, I am looking for a way to pass some arguments to ... part which will be used by auto.arima function, without explicitly mentioning names of arguments.


Solution

  • Assuming the inputs fun1, x, fun2 and args shown below the last line runs fun1.

    fun1 <- function(x, fn, ...) fn(x) + fn(...)
    x <- 3:4
    fun2 <- sum
    args <- list(1, 2)
    
    
    do.call("fun1", c(list(x, fun2), args))
    ## [1] 10