如何在内部函数中重用参数?

时间:2013-04-04 10:59:07

标签: r

我有一个函数do_something,它接收四个参数并调用内部函数get_options

do_something <- function(name, amount, manufacturer="abc", width=4){ 
    opts <- get_options(amount, manufacturer = manufacturer, width = width)
}

get_options <- function(amount, manufacturer="abc", width = 4) { 
    opts <- validate_options(manufacturer, width)
}

有时我会get_options(400),有时我想覆盖参数get_options(400, manufacturer = "def"),有时我会调用do_something("A", 400)do_something("A", 400, width=10)

通过在两个函数中为我的参数指定相同的默认值,似乎我是多余的。有没有更好的方法让他们分享这些默认值?

1 个答案:

答案 0 :(得分:7)

您可以使用省略号(...)并仅将默认值设为最低级别的函数:

do_something <- function(name, amount, ...){ 
    opts <- get_options(amount, ...)
}

get_options <- function(amount, manufacturer="abc", width = 4) { 
    opts <- validate_options(manufacturer, width)
}

您仍然可以运行以下所有内容:

get_options(400)
get_options(400, manufacturer = "def")
do_something("A", 400)
do_something("A", 400, width=10)

并且结果相同。

相关问题