This is a question regarding coding in R.
The example I provide is didactic. Suppose I have functions called 'func1' and 'func2', where each takes two arguments (let's say scalars). I want to specify another function 'applyfunction' that has three args: the last number of the function to use ('1' or '2'), and the two arguments for the function. For example, I want to do something like this (which of course doesn't work):
applyfunction(1,2,3)
where it would effectively run func1(2,3)
and
applyfunction(2,9,43)
where it would effectively run func2(9,43)
.
Any ideas?
Best, DB
You might want to look at do.call()
, which calls a function with arguments supplied in a list. It is not to hard to write a wrapper around this that does exactly what you want.
function1=function(a,b)a+b
function2=function(a,b,c)a+b+c
do.call("function1",list(1,2))
do.call("function2",list(1,2,3))
EDIT: A wrapper would be:
applyfunction=function(fun,...)do.call(fun,list(...))
applyfunction("function1",1,2)
applyfunction("function2",1,2,3)
Here's another alternative. You can add more functions to the switch
list.
func1 <- function(a, b) a + b
func2 <- function(a, b) a - b
applyfunction <- function(FUN, arg1, arg2) {
appFun <- switch(FUN,
func1, # FUN == 1
func2, # FUN == 2
stop("function ", FUN, " not defined")) # default
appFun(arg1, arg2)
}
applyfunction(1,2,3)
# [1] 5
applyfunction(2,9,43)
# [1] -34
applyfunction(3,9,43)
# Error in applyfunction(3, 9, 43) : function 3 not defined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With