Passing optional arguments inside a wrapper function of a subfunction

I have a wrapper function where I need to pass optional arguments to the specified subfunction. But there are so many different possible subfunctions that I cannot pre-specify. For reference, subfunctions exist in the environment, etc .... Consider:

funInFun<- function (x, method, ...) { method.out <- function(this.x, FUN, ...) { FUN <- match.fun(FUN) c <- FUN(this.x, ...) return(c) } d <- method.out(x, method) return(d) } data<-seq(1,10) funInFun(data, mean) # Works data<-c(NA,seq(1,10)) funInFun(data, mean, na.rm=TRUE) # Should remove the NA funInFun(c(seq(1,10)), quantile, probs=c(.3, .6)) # Shoudl respect the probs option. 
+6
source share
2 answers

You need to pass ... to method.out . Then it works fine:

 funInFun<- function (x, method, ...) { method.out <- function(this.x, FUN, ...) { FUN <- match.fun(FUN) c <- FUN(this.x, ...) return(c) } d <- method.out(x, method, ...) # <<--- PASS `...` HERE return(d) } data<-seq(1,10) funInFun(data, mean) # Works # [1] 5.5 data<-c(NA,seq(1,10)) funInFun(data, mean, na.rm=TRUE) # Should remove the NA # [1] 5.5 funInFun(c(seq(1,10)), quantile, probs=c(.3, .6)) # 30% 60% # 3.7 6.4 
+5
source

In addition to Thomas 's answer to the OP question, you may have to redirect the optional argument, which is the explicit argument to the wrapper function.

In this case, instead of repeating the standard value of the wrapped function in the shell definition, you can use missing to construct the call with the missing argument.

 f <- function(s = "world!") cat("Hello", s) f() # Hello world! g <- function(s = NULL) eval(substitute( f(s = sub_me), list(sub_me = if(missing(s)) quote(expr =) else s))) g() # Hello world! g("you!") # Hello you! 
0
source

Source: https://habr.com/ru/post/952063/


All Articles