Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect missing dot-dot-dot in generic function argument

Tags:

r

missing-data

Suppose I have a function like

z <- function(x, ...) {
  print(x)
}

If ... is missing, the function should do one thing; if ... is specified, the function should do something else with it. In this case I can use missing(...) to detect if .. is missing. But I don't find an elegant way to detect with generic methods like [.Obj(x, ...) where missing ... is still a pairlist(<emptyname>) and missing(...) = FALSE even if I don't give values.

Here are some experiments:

z <- function(x, ...) {
  cat(missing(...))
}

Obj <- function() {
  env <- environment()
  class(env) <- "Obj"
  env
}

`[.Obj` <- function(x,...) {
  cat(missing(...),"\n")
}

With the above code evaluate the following:

> z()
TRUE
> z(a=1)
FALSE
> Obj()[]
FALSE 
NULL
> Obj()[a=1]
FALSE 
NULL

However, in debug mode for Obj()[] in RStudio, it is like

Browse[1]> list(...)
Error: argument is missing, with no default
Browse[1]> missing(...)
[1] FALSE

Somehow the way that works for z() does not work for Obj()[]. Is there an elegant way with little overhead to detect whether ... is missing for the [.Obj(x, ...) case which I actually encounter?

See also: http://r.789695.n4.nabble.com/Arguments-passing-through-dot-dot-dot-lose-ability-to-check-for-missing-td4656455.html

like image 859
Kun Ren Avatar asked Oct 21 '22 03:10

Kun Ren


1 Answers

Try checking if ..1 is missing:

> `[.Obj` <- function(x, ...) missing(..1)
> Obj()[a=1]
[1] FALSE
> Obj()[]
[1] TRUE
like image 109
G. Grothendieck Avatar answered Oct 23 '22 00:10

G. Grothendieck