Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: specifying a string as an argument of a function that calls another function

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

like image 465
David Burk Avatar asked Feb 10 '11 16:02

David Burk


2 Answers

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)
like image 58
Sacha Epskamp Avatar answered Oct 23 '22 15:10

Sacha Epskamp


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
like image 31
Joshua Ulrich Avatar answered Oct 23 '22 16:10

Joshua Ulrich