Matthew Plourde
Matthew Plourde

Reputation: 44614

Custom missing function

missing returns TRUE for an argument not supplied by the caller regardless of whether the argument has a default value.

f <- function(a, b=2, c) {
   cat(missing(a), missing(b), missing(c), fill=TRUE)
}

f(a=1)
# FALSE TRUE TRUE

I'd like a version of missing that returns TRUE only for unsupplied arguments that don't have default values. I've come up with something, but it's kind of ugly.

really.missing <- function(x) {
    name.supplied <- as.character(substitute(x))
    do.call(function(y) missing(y), 
            unname(mget(name.supplied, envir=parent.frame())))
}
ff <- function(a, b=2, c) {
   cat(really.missing(a), really.missing(b), really.missing(c), fill=TRUE)
}
ff(a=1)
# FALSE FALSE TRUE

Is there a more concise way?

Upvotes: 0

Views: 66

Answers (1)

sebkopf
sebkopf

Reputation: 2375

If I understand your question correctly, how about this:

noval<- function(x) {
  tryCatch( {force(x); FALSE}, error = function(x) TRUE)
}

f <- function(a, b=2, c) {
  cat(noval(a), noval(b), noval(c), fill=TRUE)
}

f(a=1)

This noval function will force your parameter to be evaluated (which will succeed if it passed in or has a default value set but fail otherwise) and return FALSE/TRUE accordingly.

Upvotes: 1

Related Questions