Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a function name as a string

Tags:

function

r

Say I have a bunch of functions, each with something likeMyFunction.1, etc. I want to pass these functions into another function, which prints out a small report. Ideally I'd like to be able to label sections of a report by which function is being used to generate the results.

So are there any nice ways of getting the name of a predefined function as a string?

like image 937
HamiltonUlmer Avatar asked Oct 14 '09 17:10

HamiltonUlmer


People also ask

How can I call a function given its name as a string?

There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.

How do I convert a function to a string in Python?

How to Convert Python Int to String: To convert an integer to string in Python, use the str() function. This function takes any data type and converts it into a string, including integers. Use the syntax print(str(INT)) to return the int as a str , or string.

How do you call a function from its name stored in a string in Python?

Use locals() and globals() to Call a Function From a String in Python. Another way to call a function from a string is by using the built-in functions locals() and globals . These two functions return a Python dictionary that represents the current symbol table of the given source code.


2 Answers

I was wanting the same thing, and remembered library(foo) didn't need quotes, this is what it does:

package <- as.character(substitute(package)) 
like image 172
nfultz Avatar answered Sep 20 '22 19:09

nfultz


Another approach would be to pass the names of the functions into your report function, and then get the functions themselves with the get() command. For instance:

function.names <- c("which","all") fun1 <- get(function.names[1]) fun2 <- get(function.names[2]) 

Then you have the names in your original character vector, and the functions have new names as you defined them. In this case, the all function is now being called as fun2:

> fun2(c(TRUE, FALSE)) [1] FALSE 

Or, if you really want to keep the original function names, just assign them locally with the assign function:

assign(function.names[2], get(function.names[2])) 

If you run this command right now, you will end up with the all function in your ".GlobalEnv". You can see this with ls().

like image 45
Shane Avatar answered Sep 20 '22 19:09

Shane