简体   繁体   English

如何在 R 的环境中动态访问和调用 function?

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

Suppose I have a function in my environment defined as follows:假设我的环境中有一个 function 定义如下:

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.我想通过它在环境中的名称来引用上面的 function 并能够调用它来替换它的参数。 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: do.call将接受 function 名称作为字符串,因此:

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.如果 fun.name 不在 do.call 可访问的环境中,您可能需要指定 do.call 的 envir= 参数。

*** UPDATE. *** 更新。 After brief discussion with G. Grothendieck I see how to do it now:在与 G. Grothendieck 进行简短讨论后,我现在知道该怎么做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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