R check if parameters are specified: general approach -


i include in r functions general approach check if parameters have been specified. using missing() don't want specify parameter names. want make work inside arbitrary function. more specific, want able copy/paste code in function have without changing , check if parameters specified. 1 example following function:

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

try 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 function threw error, change last line like

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

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -