简体   繁体   中英

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.

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

Any suggestions?

Try substitute :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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