EvalText: Parse and evaluate a text string.

Description Usage Arguments Value Note Examples

Description

Shorthand for eval(parse(text = x, env)), frequently used with data.table, with env set to the data.table.

Usage

1
EvalText(x, env = parent.frame())

Arguments

x

string to be sent as text argument to parse.

env

environment to use for evaluation. the default parent.frame() refers to the calling environment. See note for further details.

Value

the evaluated expression eval(parse(text = x, env)).

Note

parent.frame() is a good default for env, but may lead to unusual behavior if passed to EvalText() explicitly. Default arguments are evaluated inside the execution environment of the function where they are used. However, explicitly passed arguments are evaluated inside the calling environment instead. Thus, in Example 2, EvalText("x") evaluates parent.frame() from within the execution environment of EvalText(), and finds the execution environment of fn(), where x = 2. This is the generally desired behavior. However, EvalText("x", parent.frame()) evaluates parent.frame() from within the calling environment of EvalText(), i.e. from within the execution environment of fn(). This gives the global environment, where x = 1.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# Example 1
dt <- data.table::as.data.table(mtcars)
colname <- "mpg"
dt[, amss:::EvalText(colname, dt)]
dt[, (amss:::PasteD(colname, "plus1")) := amss:::EvalText(colname, dt) + 1]

# Example 2.
x <- 1
fn <- function() {
  x <- 2
  return(c(amss:::EvalText("x"), amss:::EvalText("x", parent.frame())))
}
fn()

google/amss documentation built on May 20, 2019, 5:05 p.m.