R:传递函数参数以覆盖内部函数的默认值 [英] R: Passing function arguments to override defaults of inner functions

查看:59
本文介绍了R:传递函数参数以覆盖内部函数的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在R中,我想做这样的事情:我有一个函数f1,它带有一个带默认值的参数.k = 3.

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
}

然后我再定义一个第二个函数f2,它调用f1.

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

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

允许f2的用户在内部函数f1中覆盖k的默认值的最干净方法是什么?一种简单的解决方案是将f2重新定义为:

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.

推荐答案

最简单的解决方法是使用 ... 参数.这使您可以将任意数量的其他参数传递给其他函数:

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, ...)
}

您将看到此函数通常在使用许多可选参数(例如 plot )调用其他函数的函数中使用.

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

这篇关于R:传递函数参数以覆盖内部函数的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆