Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Insert a Function Name into a Call

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading