简体   繁体   中英

R - Call a function from function name that is stored in a variable?

I'm writing some R code and I want to store a list of Function names and what they are for in a dataframe, and then query that dataframe to determine which function to call, but I can't figure out how to do this, or if it's even possible.

As a basic example, let's assume the function name is just stored as a string in a variable, how do I call the function based on the function name stored in that variable?

MyFunc <-function() {
    # Do some stuff...
    print("My Function has been called!!!")
    return(object)
}

FuncName <- "MyFunc()"
Result <- FuncName

I need to make

Result <- FuncName

Work the same as

Result <- MyFunc()

Also, passing objects, or other variables, to the functions is not a concern for what I am doing here, so those () will always be empty. I realize passing variables like this might get even more complicated.

You could use get() with an additional pair of () .

a<-function(){1+1}                                                                                                  
var<-"a"

> get(var)()
[1] 2

To get a function from its name, try match.fun , used just like get in the answer provided by @Alex:

> match.fun(f)(1:3)
[1] 2 3 4

To call a function directly using its name, try do.call :

> a <- function(x) x+1
> f <- "a"
> do.call(f, list(1:3))
[1] 2 3 4

The advantage to do.call is that the parameters passed to the function do not have to be hardwired into the code.

Both of these approaches will make sure that the value associated with the object with the name "a" (in the above examples) is a function rather than another type of object (eg, a numeric, a data.frame, ...).

Consider the following:

# works fine
> get("c")(1,2,3)
[1] 1 2 3

# create another object called "c"
> c <- 33
> get("c")
[1] 33

#uh oh!!
> get("c")(1,2,3)
Error: attempt to apply non-function

# match.fun with return a function; it ignores
# any object named "c" this is not a function.
> match.fun("c")(1,2,3)
[1] 1 2 3

# same with do.call
> do.call("c", list(1,2,3))
[1] 1 2 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM