简体   繁体   English

如何使用该调用的另一个参数以及在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?

I am trying to write a function that will take an expression as an argument, and then evaluate that expression in the context of 1) another argument of the function, and 2) an object created inside the function itself. 我正在尝试编写一个将表达式作为参数的函数,然后在1)函数的另一个参数和2)在函数内部创建的对象的上下文中评估该表达式。

I'm having some problems getting the environment to work. 我在使环境正常工作时遇到了一些问题。 Does anyone know how to do this? 有谁知道如何做到这一点?

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)

Results in the error: Error in eval(model) : object 'es' not found 错误结果:eval(model)中的错误:找不到对象'es'

Any suggestions? 有什么建议么?

Try substitute : 尝试substitute

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

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

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