3

I am generating functions programatically by calling into a Java library, it looks something like this

f <- getFunction("javaFunctionName")

I can generate these just fine, but what I would like to know is if it is possible to give those functions names in the R environment.

functionNames <- c("func1", "func2", "func3")

lapply(functionNames, getFunction)

After performing the lapply I would be able to call the functions I made by those names:

func1(args)
func2(args)
func3(args)

I looked at this discussion and either I am missing something or it is not the same as what I am trying to do.

Hope I have been clear and any help is appreciated. Thank you for your time.

Community
  • 1
  • 1
jwilley44
  • 173
  • 6
  • What about one function: func(1, args), func(2, args) etc? I don't think dynamically creating functions is ever a good idea. – sashkello Jan 31 '14 at 03:56
  • I could create a function that took the name and the args and applied it. The main reason of dynamically creating the functions with the actual names is that it would stay consistent with our other tools. For my own edification, why is dynamically creating functions not a good idea? – jwilley44 Jan 31 '14 at 04:56
  • "Dynamically creating a function" is very close to "late binding" and has its place. I'll trust you that yours is a valid use. – Matthew Lundberg Jan 31 '14 at 05:02
  • 1
    The question is why would you want to create several functions when you can have one which is easily called with any parameter `x` which can be a variable, as `func(x, args)`. You can then put it in a loop, reuse it etc. (can't do it with several functions, not without some unnecessary effort and mess in your code). In case of variables this is what arrays are for and you can create array of functions if you insist in R as well: http://stackoverflow.com/questions/12481404/how-to-create-a-vector-of-functions – sashkello Jan 31 '14 at 05:06

1 Answers1

3

If I understand you correctly, doesnt the following work?

functionNames <- c("func1", "func2", "func3")

yourJavaFunc <- function() "myJavaFunc"

assignFunctions <- function(fcts){
  lapply(fcts, function(x) {
    assign(x, yourJavaFunc, envir = .GlobalEnv) # add your getJavaFunction locic here
  })
}

assignFunctions(functionNames)
Miriam
  • 471
  • 5
  • 20