[R] pass functions and arguments to function
Duncan Murdoch
murdoch at stats.uwo.ca
Tue Dec 29 23:53:42 CET 2009
On 29/12/2009 5:24 PM, Hao Cen wrote:
> Thanks. I don't know how many functions there will be.
>
> What if g1, g2, g3 have variable number of parameters? say g1 has parg1a,
> parg1b, and g3 has parg3a, parg3b, parg3c, parg4d.
pars could be a list of lists of parameters instead of a list of
parameters, then the calls could be
do.call(fs[[i]], pars[[i]])
But it's very unlikely that you are doing something that's a good idea.
Duncan Murdoch
>
> f <- function(X, fs, pars) {
> process1(X)
> for (i in 1:length(fs))
> fs[[i]](pars[[i]]) # doesn't work here
>
> process2(X)
>
> }
>
>
> On Tue, December 29, 2009 4:57 pm, Duncan Murdoch wrote:
>> On 29/12/2009 3:08 PM, Hao Cen wrote:
>>
>>> Hi,
>>>
>>>
>>> I wonder how to pass several functions and their arguments as arguments
>>> to a function. For example, the main function is
>>>
>>> f = function(X ) { process1(X) ...
>>>
>>>
>>>
>>> process2(X) }
>>>
>>>
>>> I have a few functions that operate on X, e.g. g1(X, par1), g2(X,
>>> par2), g3(X, par3). par1, par2 and par3 are parameters and of different
>>> types. I would like to pass g1, g2, g3 and their arguments to f and g1,
>>> g2, g3 may appear to be in different orders. So that final effect of the
>>> passing is
>> Just pass them. If you know there are three functions, set up f as
>>
>>
>> f <- function(X, f1, f2, f3, par1, par2, par3) { process1(X) f1(X, par1)
>> f2(X, par2) f3(X, par3) process2(X) }
>>
>>
>> and call it as
>>
>> f(X, g1, g2, g3, par1, par2, par3)
>>
>> If you don't know how many functions there will be, put them in a list:
>>
>>
>> f <- function(X, fs, pars) { process1(X) for (i in 1:length(fs))
>> fs[[i]](pars[[i]]) process2(X) }
>>
>>
>> and call it as
>>
>> f(X, list(g1, g2, g3), list(par1, par2, par3))
>>
>> Duncan Murdoch
>>
>>
>>> f = function(X ) { process1(X) g1(X, par1) g2(X, par2) g3(X, par3)
>>> process2(X) }
>>>
>>>
>>> If I pass g2(X, par2),g3(X, par3), g1(X, par1) to f, I would expect to
>>> get the effect of f = function(X ) { process1(X) g2(X, par2) g3(X, par3)
>>> g1(X, par1) process2(X) }
>>>
>>>
>>> Appreciate any suggestions.
>>>
>>>
>>> thanks
>>>
>>> Jeff
>>>
>>>
>>>
>>> ps please ignore my previous blank subject email. It was accidentally
>>> sent before the letter was completed.
>>>
>>> ______________________________________________
>>> R-help at r-project.org mailing list
>>> https://stat.ethz.ch/mailman/listinfo/r-help
>>> PLEASE do read the posting guide
>>> http://www.R-project.org/posting-guide.html
>>> and provide commented, minimal, self-contained, reproducible code.
>>
>>
>
More information about the R-help
mailing list