【问题标题】: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?如何使用该调用的另一个参数以及在 R 的函数环境中创建的对象来评估函数调用的一个参数?
【发布时间】:2018-02-14 20:10:44
【问题描述】:

我正在尝试编写一个将表达式作为参数的函数,然后在 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”

有什么建议吗?

【问题讨论】:

  • 您可以使用mu &lt;- eval(parse(text = model))model 作为字符参数
  • 谢谢安德烈;我知道您的解决方案有效,但我更愿意了解如何为此使用惰性评估..

标签: r environment


【解决方案1】:

试试substitute:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-02
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多