Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to optionally supply an argument to a function in R?

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.

like image 333
rhombidodecahedron Avatar asked Mar 16 '23 15:03

rhombidodecahedron


1 Answers

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

like image 78
G. Grothendieck Avatar answered Apr 07 '23 07:04

G. Grothendieck