如何使用该调用的另一个参数评估函数调用的一个参数,以及在 R 中的函数环境中创建的对象?

How to evaluate one argument of a function call using another argument of that call, and an object created inside the function environment in R?

我正在尝试编写一个函数,它将一个表达式作为参数,然后在 1) 函数的另一个参数和 2) 在函数本身内部创建的对象的上下文中计算该表达式。

我在让环境正常工作时遇到了一些问题。有人知道怎么做吗?

myfun <- function(es = .5, model = es * x[, 1]){
  x <- matrix(rnorm(300), ncol = 3)
  mu <- eval(model)
  mu
}

myfun(es = .8, model = es * x[, 1] + es * x[, 1]^2 + es * x[, 1]^3)

错误结果:eval(model) 错误:找不到对象 'es'

有什么建议吗?

尝试 substitute:

myfun <- function(es = .5, model = es * x[, 1]){
    x <- matrix(rnorm(300), ncol = 3)
    mu <- eval(substitute(model))
    mu
}