On Sat, Feb 1, 2014 at 11:40 AM, Hai Qian <hqian@gopivotal.com> wrote:

> I know using eval is not optimal and maybe bad, but how to avoid using eval
> in the following example
>
> func1 <- function(dat, eval.this) {
>     eval(parse(text = paste0("with(dat, ", eval.this, ")")))
> }
>
> dat <- data.frame(x = 1:2, y = 2:3)
>
> func1(dat, "x*2+y")
>
> func1(dat, "sin(x)*cos(y)")
>
> Here eval.this is a string that contains whatever the user wants to
> evaluate. I wonder whether there is a neat way to avoid using eval in this
> case? So far I have not figured out a way to do this.
>
>
Since the string is arbitrary R code ultimately it will have to be pushed
through the R interpreter but we can avoid the superficial act of calling
'eval' by punting to some other function which in turn invokes 'eval' like
this:

   func2 <- function(dat, s) do.call("with", list(dat, parse(text = s)))

'func2' can be run like this:

> func2(dat, "x*2+y")
[1] 4 7
> func2(dat, "sin(x)*cos(y)")
[1] -0.3501755 -0.9001976

Note that 'with' dispatches to 'with.default' which in turn invokes `eval`:

> with.default
function (data, expr, ...)
eval(substitute(expr), data, enclos = parent.frame())
<bytecode: 0x0000000005db6790>
<environment: namespace:base>

	[[alternative HTML version deleted]]


