Check function input in another function - pass all parameters

I have a complex function with many parameters. To make the code more readable, I thought that I could transfer the validation of input to some other function. As in the following example:

complex_function <- function(a=NA, b=NA, c=NA, d=NA, e=NA, f=NA, g=NA, h=NA) {
  check_inputs(a=a, b=b, c=c, d=d, e=e, f=f, g=g, h=h)
  # ... rest of the function
}

check_inputs= function(a=NA, b=NA, c=NA, d=NA, e=NA, f=NA, g=NA, h=NA) {
  if(is.na(a) & is.na(c)) {
    stop("Not valid inputs - message 1")
  } else if (is.na(h)) {
    stop("Not valid inputs - message 2")
  } 
  # long list of other controls
}

Is it possible to call check_inputswithout explicitly specifying all parameters? Something like check_inputs(get_all_arguments_of_parrent_function)? Is there a better way to approach this?

+4
source share
1 answer

Perhaps this small example will help:

foo <- function(x,y){
    foo_call <- as.list(match.call()[-1])
    do.call(check_args,foo_call)
}

check_args <- function(x,y){
    print(x)
    print(y)
}

match.callreturns a language object containing the original function call. I am removing the first element because it is the name of the function. The remaining elements are arguments and their meanings. Then we can just pass it on do.callto another function check_args.

+5

All Articles