I would like to write a wrapper function for two functions that take optional arguments.
Here is an example of a function fun
to wrap funA
and funB
funA <- function(x = 1, y = 1) return(x+y)
funB <- function(z = c(1, 1) return(sum(z))
fun <- function(x, y, z)
I would like fun
to return x+y
if x
and y
are provided, and sum(z)
if a vector z
is provided.
I have tried to see how the lm
function takes such optional arguments, but it is not clear exactly how, e.g., match.call
is being used here.
After finding related questions (e.g. How to use R's ellipsis feature when writing your own function? and using substitute to get argument name with )), I have come up with a workable solution.
My solution has just been to use
fun <- function(...){
inputs <- list(...)
if (all(c("x", "y") %in% inputs){
ans <- funA(x, y)
} else if ("z" %in% inputs){
ans <- funB(z)
}
Is there a better way?
Note: Perhaps this question can be closed as a duplicate, but hopefully it can serve a purpose in guiding other users to a good solution: it would have been helpful to have expanded my search to variously include ellipsis
, substitute
, in addition to match.call
.