4

In R, I would like to do something like this: I have a function f1, that has an argument with a default value; k=3.

f1 = function(x,k=3){
    u=x^2+k
    u
}

I then later define a second function, f2 that calls f1.

f2 = function(z,s){
    s*f1(z)
}

What's the cleanest way to allow users of f2 to override the default value of k in the inner function f1? One trivial solution is to redefine f2 as:

f2 = function(z,s,K){
    s*f1(z,K)
}

However, I feel this might be cumbersome if I'm dealing with a large heirarchy of functions. Any suggestions? Thanks.

bigO6377
  • 1,256
  • 3
  • 14
  • 28

1 Answers1

5

The easiest way to deal with this is using the ... argument. This allows you to pass any number of additional arguments to other functions:

f1 = function(x,k=3){
    u=x^2+k
    u
}

f2 = function(z,s, ...){
    s*f1(z, ...)
}

You'll see this commonly used in functions which call others with many optional arguments, for example plot.

Scott Ritchie
  • 10,293
  • 3
  • 28
  • 64
  • 1
    More information [here](http://stat.ethz.ch/R-manual/R-devel/library/base/html/Reserved.html) and [there](http://cran.r-project.org/doc/manuals/r-release/R-intro.html#The-three-dots-argument) –  Sep 03 '13 at 22:45