How to reuse arguments in an internal function?

I have a function do_somethingthat takes four arguments and calls an internal function 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)
}

Sometimes I do get_options(400), in other cases I want to override the arguments get_options(400, manufacturer = "def"), otherwise I call do_something("A", 400)or do_something("A", 400, width=10).

It seems like I'm redundant by specifying the same default values ​​for my arguments in both functions. Is there a better way for them to share these defaults?

+5
source share
1 answer

You can use ellipsis ( ...) and specify default values ​​only for a lower-level function:

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

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

You can still run everything below:

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

and with the same results.

+7
source

All Articles