substitute() looks at a function argument and instead of seeing the value, it sees the code used to compute the value. substitute() returns an expression.
substitute() works because function arguments are represented by a special type of object called a promise. A promise captures the expression needed to compute the value and the environment in which to compute it.
substitute() is often paired with deparse(). That function takes the result of substitute(), an expression, and turns it into a character vector.
One important feature of deparse() to be aware of when programming is that it can return multiple strings if the input is too long.
eval() takes an expression and evaluates it in the specified environment.
quote(). It captures an unevaluated expression like substitute(), but doesn’t do any of the advanced transformations that can make substitute() confusing. quote() always returns its input as is.
So if you only provide one argument, it will evaluate the expression in the current environment. This makes eval(quote(x)) exactly equivalent to x, regardless of what x is.
eval()’s second argument need not be limited to an environment: it can also be a list or a data frame.
=====================================
Cited from Tips on non-standard evaluation in R
In fact, eval(expr, envir, enclos) basically follows the following logic to evaluate a quoted expression:
- If envir is an environment, then evaluate expr in envir by looking for symbols all the way along envir and its parent environments until found.
- If envir is a list, then evaluate expr given the symbols defined in the list; Whenever a symbol is not found in the list, the function will go to enclos environment to find along the chain until found.
- If a symbol is not found until the empty environment (the only environment having no parent) is reached, an error occurs.
Non standard evaluation from another function in R
No comments:
Post a Comment