Denis
Denis

Reputation: 12087

How do I dynamically access and call a function in R's environment?

Suppose I have a function in my environment defined as follows:

abc <- function(x, a, b=23) { return(paste(x, a, b, sep=';')) }

I would like to get a reference to the above function by its name in the environment and be able to call it replacing its parameters. So an example:

> fun.abc <- get.fun.from.env('abc')  #`fun.abc` should be the same as `abc` (above)
> x <- 123
> addl.params <- c(a=245, b=345)
> do.call(fun.abc, list(x, addl.params))
123;245;345

How would I implement this idea?

Upvotes: 1

Views: 255

Answers (2)

Denis
Denis

Reputation: 12087

*** UPDATE. After brief discussion with G. Grothendieck I see how to do it now:

> fun.abc <- get('abc')
> x <- 123
> addl.params <- c(a=245, b=345)

#somewhere else when I have a pointer to fun.abc
> do.call(fun.abc, c(x, as.list(addl.params)))

*** THIS WAS MY FIRST ATTEMPT AT THIS:

I came close to what I wanted to do in a somewhat different way. Hoping someone might be able to propose a way to achieve what I originally intended...

apply.fun <- function(func.id, x, ...) {
  func.def <- load.func.spec.from.db(func.id)
  def.args <- eval(str2lang(func.def$params))
  args <- replace(def.args, names(...), as.list(...))

  do.call(func.def$fun, list(x=x, unlist(args)))
}

Upvotes: 0

G. Grothendieck
G. Grothendieck

Reputation: 270428

do.call will accept a function name as a string so:

fun.name <- "abc"
do.call(fun.name, c(x, as.list(addl.params)))
## [1] "123;245;345"

You may need to specify the envir= argument of do.call if fun.name is not in an environment reachable from the do.call.

Upvotes: 2

Related Questions