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 really want it done 'by the numbers':
> applyfunction=function(n,a,b){get(paste("func",n,sep=""))(a,b)}
> func1=function(a,b){a+b}
> func2=function(a,b){a*b}
> applyfunction(1,4,3)
[1] 7
> applyfunction(2,4,3)
[1] 12
Uses get and paste to get the function associated with a name.
What about using one of the functions variables as a switch?
func1 <- function(x,y,z) {
## Function One stuff goes here
if (x == 1) {
var1 <- 1
}
## Function Two stuff goes here
if (x == 2) {
var1 <- 2
}
return(var1)
}
And, you get to use the same function, with the switch being the variable "x":
> func1(1,1,1)
[1] 1
> func1(2,1,1)
[1] 2
Here an alternate to switch or paste, just use indexing to select from a list:
function1=function(a,b) a+b
function2=function(a,b,c) a*b
applyfunc <- function(n, aa, bb){ c(function1, function2)[[n]](aa,bb) }
applyfunc(1, 4, 3)
# [1] 7
applyfunc(2, 4, 3)
#[1] 12
applyfunc(3, 4, 3)
# Error in c(function1, function2)[[n]] : subscript out of bounds
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.