【问题标题】:How to reuse arguments in an inner function?如何在内部函数中重用参数?
【发布时间】:2013-04-04 10:59:06
【问题描述】:

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

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

【问题讨论】:

  • 我很难在这里看到一个问题。你的例子不是特别有启发性

标签: r


【解决方案1】:

您可以使用省略号 (...) 并且只为最低级别的函数提供默认值:

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)

结果相同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-13
    • 1970-01-01
    • 2014-10-13
    • 1970-01-01
    • 2017-09-08
    • 2021-06-10
    • 2013-06-23
    • 1970-01-01
    相关资源
    最近更新 更多