3

Envision

examplefn <- function(x = NULL, ...){str(x)}

I'm trying to get this function to honor the implicit x = NULL. Consider the following:

For a call using both x and ... this results as expected in:

> examplefn(1,2)
num 1

If using an explicit x = NULL, the behavior also is as expected:

> examplefn(x = NULL,2)
NULL

However, when attempting (and expecting the usage of x = NULL from the function definition, I get:

> examplefn(2)
num 2

Implying, that the call is evaluated by argument order, disregarding the x = NULL definition.

How can the latter be prevented?

balin
  • 1,554
  • 1
  • 12
  • 26
  • `x = NULL` in the definition is a default value if `x` is missing. In `examplefn(2)` you basically set `x = 2`. You wish `x` to always be `NULL` and `examplefn(2)` to be equal to `examplefn(NULL,2)`? – niko Jan 30 '19 at 09:15
  • Yes, that's the goal. I'm clearly not understanding the evaluation, but I was expecting the unnamed `2` to keep representing the ellipse ... – balin Jan 30 '19 at 09:18
  • 1
    You might benefit from reading this section of the language definition (I even recommend reading the whole document): https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Argument-matching – Roland Jan 30 '19 at 10:05

1 Answers1

2

The definition x = NULL is only used if no x value is provided. So when writing examplefn(2) what R reads is examplefn(x = 2) (as x is argument number 1) and thus the result.

If you want to circumvent this, here are a few approaches:

1. By creating two functions

fun0 <- function (x, ...) str(x) 
fun1 <- function (...) fun0(NULL, ...)
fun1(2)
# NULL

2. Another approach is by naming you arguments, e.g.

fun2 <- function (x = NULL, y) str(x)
fun2(y = 2) 
# NULL

3. Another way, maybe the most convenient for you, is simply to reorder the arguments, see

fun3 <- function (..., x = NULL) str(x)
fun3(2)  
# NULL

4. Finally, here is also a (trivial) possibility - setting x <- NULL inside the function

fun4 <- function (...) {
  x <- NULL
  str(x)
}
fun4(2)    
# NULL

But I am assuming you have reasons to want x to be an argument.

niko
  • 5,253
  • 1
  • 12
  • 32
  • 3. is indeed the most convenient. Thank you. – balin Jan 30 '19 at 09:32
  • In my actual application, however, I'm loosing the option to pipe (`magrittr`) the x argument (it's a `list`) - if it's `NULL` it's created, modified if given ... – balin Jan 30 '19 at 09:38