R: Passing function arguments to override defaults of inner functions

我只是一个虾纸丫 提交于 2021-01-27 10:38:11

问题


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:


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.



来源:https://stackoverflow.com/questions/18602407/r-passing-function-arguments-to-override-defaults-of-inner-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!