Home > Software engineering >  Insert a Function Name into a Call
Insert a Function Name into a Call

Time:11-25

I have a long script wherein I have a section at the top which is dedicated to assumptions and other hardcodes. By means of context, it's an asset allocation script wherein one of the hardcodes that is chosen is the method by which momentum is calculated, for which I have various functions. I realize that one way in which I could change the code is simply to change the function used in the body of the code; however, my preference would be to leave the body untouched and only change the name of the function to be used within the assumptions section.

By means of an extremely simple toy example, let's say I have the following two lines of code:

selected_function = "sum"
temp_data = c(2,3,4)

How would I allow whichever function is saved in the variable selected_function to be the calling function on the temp_data data set (i.e., if I want to change it to "mean", etc.) and allow that function to be applied to the data.

CodePudding user response:

If you have a function name as a string, you get can get the function itself with getFunction(). That will return a function and you can then pass your values to that returned function. For example.

selected_function = "sum"
temp_data = c(2,3,4)
getFunction(selected_function)(temp_data)
  •  Tags:  
  • r
  • Related