在另一个函数内定义函数的优雅方式

Fra*_*ell 4 r

我想建造

f <- function(...) {
   g <- function(x) x ^ 2
   list(...)
}
Run Code Online (Sandbox Code Playgroud)

所以我可以调用使用f(g(4))并产生list(...)结果list(16).

一般来说,我将定义几个临时函数f,用户可以在调用时调用它们f(...).

我已经尝试过assign,newenvironment但刚刚变得更加困惑.感谢您提供优雅的解决方案.

想要这个的原因是我想要一个Hmisc包中的函数,drawPlot能够让用户指定一般命名的函数作为构建一系列图形元素的输入,我不想保留这些泛型类型的名称.例如:

d <- drawPlot(Curve(), Points())   # interactively make a curve and
                                   # a set of points
Run Code Online (Sandbox Code Playgroud)

Jos*_*ien 7

我猜你实际上需要比这更详细的东西,但以下是你在提供的例子中所要求的:

f <- function(...) {
   g <- function(x) x ^ 2
   list(eval(substitute(...)))
}

f(g(4))
# [[1]]
# [1] 16
Run Code Online (Sandbox Code Playgroud)

或者,如果用户可以提供一个或多个函数调用,如下所示:

f <- function(...) {
   g <- function(x) x ^ 2
   h <- function(x) 100*x
   cc <- as.list(substitute(list(...))[-1])
   res <- list()
   for(i in seq_along(cc)) {
       res[[i]] <- eval(cc[[i]])
   }
   res
}
f(g(4), h(5))
# [[1]]
# [1] 16
# 
# [[2]]
# [1] 500
Run Code Online (Sandbox Code Playgroud)