aymer
aymer

Reputation: 329

R check if parameters are specified: general approach

I would like to include in my R functions a general approach to check if all parameters have been specified. I could do this by using missing() but I don't want to specify the parameter names. I want to make it work inside any arbitrary function. More specific, I want to be able to just to copy/paste this code in any function that I have without changing it and it will check if the parameters are specified. One example could be the following function:

tempf <- function(a,b){
argg <- as.list((environment()))
print(argg)
}

tempf(a=1, b=2)

Upvotes: 2

Views: 184

Answers (1)

Richie Cotton
Richie Cotton

Reputation: 121077

Try this function:

missing_args <- function()
{
  calling_function <- sys.function(1)
  all_args <- names(formals(calling_function))
  matched_call <- match.call(
    calling_function, 
    sys.call(1), 
    expand.dots = FALSE
  )
  passed_args <- names(as.list(matched_call)[-1])
  setdiff(all_args, passed_args)
}

Example:

f <- function(a, b, ...)
{
  missing_args()
}

f() 
## [1] "a"   "b"   "..."
f(1) 
## [1] "b"   "..."
f(1, 2) 
## [1] "..."
f(b = 2) 
## [1] "a"   "..."
f(c = 3) 
## [1] "a" "b"
f(1, 2, 3)
## character(0)

If you'd rather the function threw an error, then change the last line to something like

  args_not_passed <- setdiff(all_args, passed_args)
  if(length(args_not_passed) > 0)
  {
    stop("The arguments ", toString(args_not_passed), " were not passed.")
  }

Upvotes: 4

Related Questions