For the sake of example, let's say I have a function with several optional arguments:
result <- function_with_several_optional_arguments(a=1, b=2, c=3)
Depending on a variable foo
, I want to either supply d=1
or let it take its default value, which is unknown to me.
I could do
if (foo) {
result <- function_with_several_optional_arguments(a=1, b=2, c=3, d=1)
} else {
result <- function_with_several_optional_arguments(a=1, b=2, c=3)
}
but this quickly leads to a lot of code duplication - especially if I want to conditionally supply many arguments.
How can I conditionally supply an argument or leave it default?
Ideally I'd do something like
result <- function_with_several_optional_arguments(a=1, b=2, c=3, ifelse(foo, d=1))
but I don't know if there's any support for something like that.
Use do.call
:
Args <- list(a = 1, b = 2, c = 3)
if (foo) Args$d <- 1
do.call("fun", Args)
The second line could also be written: Args$d <- if (foo) 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With