简体   繁体   中英

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?

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.

*** 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)))
}

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