R missing() with variable names
You probably first tried something like missing(as.name(formalNames[1]))
or missing(formalNames[1])
and found that they do not work.
The reason they don't is that missing()
is one of those odd functions -- library()
and debug()
are a couple of others -- that will accept as an argument either a name or a character representation of a name. That's 'nice' in the sense that missing(a)
and missing("a")
will both check whether the function call included a supplied argument a
; it's not so nice when you do missing(formalNames[1])
and it goes off to look for a non-existent argument named formalNames[1]
.
The solution is to use do.call()
, which evaluates the elements of its second argument before passing them on to the function given in its first argument. Here's what you might do:
demoargs <- function(a=3, b=2, d) {
formalNames <- names(formals()) # get variable names: a, b, d
do.call(missing, list(formalNames[1]))
}
## Try it out
demoargs(a=42)
# [1] FALSE
demoargs()
# [1] TRUE