Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function with default Parameter on condition

Tags:

r

I have a function foo that takes one argument and has a default parameter

foo <- function(b = 2) b

I want to call this function from another function bar.

bar <- function(a, b = NULL){
    a * foo(b = ???)
}
  • If b is provided in bar I want to call foo with this parameter
  • if not I want to call foo with its default parameter.

How can I do that?

(I couldn't find a good title for this question, so please change it if you know a better one.)

like image 706
Georgery Avatar asked Dec 21 '25 18:12

Georgery


1 Answers

You can use the ... argument:

foo <- function(b = 2) b
bar <- function(a, ...) {
  a * foo(...)
}

bar(a=5)
bar(3, b=3)
bar(3, 7)
like image 92
jogo Avatar answered Dec 24 '25 08:12

jogo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!