Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing optional arguments inside a wrapper function to a sub-function

Tags:

function

r

I have a wrapper function, where I need to pass optional arguments to the sub-function specified. But there are so many different possible sub-functions that I can't pre-specify them. For reference, the sub-functions 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. 
like image 748
Daniel Egan Avatar asked Aug 19 '13 21:08

Daniel Egan


People also ask

How do you pass an optional parameter to a function in Python?

You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function.

What is an optional argument in functions?

Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates. When you use named and optional arguments, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list.

What is an optional argument in R?

Optional arguments are ones that don't have to be set by the user, either because they are given a default value, or because the function can infer them from the other data you have given it. Even though they don't have to be set, they often provide extra flexibility.

Are function call arguments optional?

So, it is optional during a call. If a value is provided, it will overwrite the default value. Any number of arguments in a function can have a default value.


1 Answers

You need to pass the ... 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
like image 142
Thomas Avatar answered Nov 03 '22 01:11

Thomas