Cris
Cris

Reputation: 335

How to pass down a missing argument in R?

I have a function that internally calls another function that can have missing arguments. If I do not define a default NULL value for the argument in the high-level function the missing argument is correctly passed down. However, in the function documentation, I would like to explicitly indicate that the argument is optional by assigning a default NULL value to it.

In the following MWE, how could I make high.foo2() work more like high.foo1()?

low.foo <-  function(y = NULL) if(missing(y)) cat ('y is missing') else print(y)

high.foo1 <-  function(y) low.foo(y = y)
high.foo1()
# > y is missing

high.foo2 <-  function(y = NULL) low.foo(y = y)
high.foo2()
# > NULL

PD1. Not a duplicate of R how to pass a (potentially) missing argument?

Upvotes: 2

Views: 311

Answers (1)

akrun
akrun

Reputation: 886938

An option to capture the argument and check if it is "NULL"

high.foo2 <-  function(y = NULL) {
  if(deparse(substitute(y)) == "NULL") low.foo() else low.foo(y = y)

}

-testing

high.foo2()
y is missing

Or may use is.null

high.foo2 <-  function(y = NULL) {
  if(is.null(substitute(y))) low.foo() else low.foo(y = y)

}
high.foo2()
y is missing

Upvotes: 1

Related Questions