R - Call a function from function name that is stored in a variable?
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:
> a <- function(x) x+1
> f <- "a"
> match.fun(f)(1:3)
[1] 2 3 4
To call a function directly using its name, try do.call
:
> params <- list(x=1:3)
> do.call(f, params)
[1] 2 3 4
The advantage to do.call
is that the parameters passed to the function can change during execution (e.g., values of the parameter list
can be dynamic at run time or passed by the user to a custom function), rather than being hardwired in the code.
Why do I suggest match.fun
or do.call
over get
? Both match.fun
and do.call
will make sure that the character
vector ("a"
in the above examples) matches a function rather than another type of object (e.g., 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 will 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