Nussig
Nussig

Reputation: 291

Check which function arguments are missing/NULL

I actually have two questions which both arose from a lack of understanding how arguments in an R function are handled.

  1. I would like to get a vector indicating which arguments of a function f(x,y) are actually missing. Is there a more elegant way than the following solution:

    f <- function(x, y) {
      c(missing(x), missing(y))
    }
    
  2. I also implemented a function which returns a logical variable indicating whether an argument is NULL:

    g <- function(x, y) {
      args_names <- as.list(environment())
      sapply(args_names, is.null)
    }
    

    While this functions works as intended, I am struggling to understand why g(y=1) does not return a TRUE for the first argument:

    > g(y=1)
        x     y 
    FALSE FALSE 
    

Upvotes: 0

Views: 336

Answers (2)

mnel
mnel

Reputation: 115382

Using sapply, you could go about it this way (and hope not too many kittens are killed:

f1 <- function(x,y) {
  sapply(names(formals()), function(arg) {
    eval.parent(call('missing', as.name(arg)), n=3)
  })
}

Upvotes: 2

csgillespie
csgillespie

Reputation: 60452

  1. This seems a reasonable thing to do. Of course, if you had many more arguments you could think about sapply

  2. For your second question why not just return the args and see

    R> g <- function(x, y) {
    +    as.list(environment())
    + }
    R> args = g(10)
    R> str(args$y)
     symbol
    

    Of course the next question is what is a symbol, taken from manual of all knowledge

Symbols refer to R objects. The name of any R object is usually a symbol. Symbols can be created through the functions as.name and quote. Symbols have mode "name", storage mode "symbol", and type "symbol". They can be coerced to and from character strings using as.character and as.name. They naturally appear as atoms of parsed expressions, try e.g. as.list(quote(x + y)).

Upvotes: 2

Related Questions