R: Passing function arguments to override defaults of inner functions

1.8k views Asked by At

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.

1

There are 1 answers

1
Scott Ritchie On

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.