I would like to use different functions as function arguments in R where the arguments of the function arguments might be different. I have seen this post which describes the case where one can use different function arguments with the same argument for each function. Here is an example of what I would like:
f <- function(func, x, y) {
return(func(x, y))
}
func1 <- function(x) {
return(x^2)
}
func2 <- function(x, y) {
return(x*y)
}
f(func1, 2) # not working: Error in func(x, y) : unused argument (y)
f(func1, 2, 3) # not working Error in func(x, y) : unused argument (y)
f(func2, 2, 3) # works
What I would like to be able to do is include a range of arguments (i.e. x, y etc. above) for f
but, when writing the function to use as function argument (e.g. func1
and func2
), not have to include all arguments in that function. i.e. I want to be able to write func1(x)
but not have include y
as an argument. Setting default parameters does not help and I seem to not be able to use ...
in the right way either.
CodePudding user response:
Since you have differing arguments, I believe if you replace the inputs with ...
may help:
f <- function(func, ...) {
func <- match.fun(func) # Rui Barradas's comment to avoid matching with other objects
return(func(...))
}
func1 <- function(x, ...) {
return(x^2)
}
func2 <- function(x, y) {
return(x*y)
}
f(func1, 2)
f(func1, 2, 3)
f(func2, x = 2, y = 3)
Output:
# > f(func1, 2)
# [1] 4
# > f(func1, 2, 3)
# [1] 4
# > f(func2, x = 2, y = 3)
# [1] 6