[R] changing default arguments of a function and return the modified function as a result
David Winsemius
dwinsemius at comcast.net
Fri Jun 26 23:28:21 CEST 2009
On Jun 26, 2009, at 12:52 PM, Miguel Bernal wrote:
> Dear R-users,
>
> I am trying to develop a function that takes another function as an
> argument,
> changes its default values and returns a list of things, among which
> the
> initial function with its default arguments changed. An example of
> what i
> will like to obtain below:
>
> ## initial function
>
> myfun <- function(x, a=19, b=21){ return(a * x + b) }
>
> ## this is the function i will like to create
> ## (does not work as it is written here)
>
> mysecond.fun <- function(a, b, c = myfun(a=2, b=15)){
^^^^^^^^^^^^^^^^^^
Two things: a) I doubt that is possible in that manner and b) you
couldn't possibly get myfun to work, because you are not passing it
the correct number of arguments.
> return(list(a=a, b=b c=c))
^
Third concern, missing comma.
> }
>
> So I would be able to call:
>
> mysecond.fun$c(x=12)
Not in this language. Maybe in some other. Maybe you are in the wrong
help list? You should instead provide a specification of the inputs
and outputs you expect rather than a hashed up view of how you think R
should accept functional arguments.
Perhaps something like this:
myfun <- function(x, a=19, b=21){ return(a * x + b) }
mysecond.fun <- function(x, a, b){ c <- myfun(x, a=2, b=15)
list(a=a, b=b, c=c) }
> mysecond.fun(x=12, 2 , 3)
$a
[1] 2
$b
[1] 3
$c
[1] 39
> # c= 2 * 12 + 15
>
> And this will be equivalent of calling:
>
> myfun(x=12, a=2, b=15 ) ## i.e. i have changed the default values of
> myfun and
> ## stored it in a new function mysecond.fun$c
>
> Any help will be greatly appreciated!
>
> Miguel Bernal.
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
More information about the R-help
mailing list