5

我有一个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).

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

4

1 回答 1

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)

并具有相同的结果。

于 2013-04-04T11:08:22.707 回答