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?
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 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.
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.
I was wanting the same thing, and remembered library(foo)
didn't need quotes, this is what it does:
package <- as.character(substitute(package))
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With