Code Comments

Code Comments

Tips and short tutorials on various programming technologies

Code Comments RSS Feed
 
 
 
 

Pass Parameters to a Dynamically Invoked Function in R

In my last post, I explained a nifty way to invoke a function dynamically when you have the name of the function in a character object (in R). However, this didn’t explain how you could pass parameters to that function. I found a way to do this, which I will explain below, though it is possible that there is a simpler way to do it, of which I am not aware. But the way I describe should be very flexible for all types of dynamic invocation.

Before I get into the details, I will explain a possible use case for this type of functionality. It might seem far fetched, but it’s the way I’m approaching one of my research tasks right now, at least as a workaround until I can find a more elegant way to do it. So…most of my code for this project is written in Java. But I need to be able to do some statistical processing in R (which has far richer statistical capabilities than Java). The way I’m approaching this is to communicate between Java and R using command-line invocation (I can provide more details if anyone is interested). I need to tell R via the command line that it should load source code from a given file and invoke a specific function using specific parameters. Then in the R code, it needs to parse those values and then call the functions specified. Hopefully that made sense…let me know if not.

Anyway, here’s how you do it. Suppose you had a function like this:

x = function(param1, param2)
{
  print(paste("value of param1:", param1))
  print(paste("value of param2:", param2))
}

The normal way you would invoke this would be:

x("abc", "def")

To invoke it dynamically, you could do this:

eval(call("x", "abc", "def"))

Leave a Reply