Tim
Tim

Reputation: 7464

R: passing values to eval in nested functions

I want to pass some query to lower level function that uses 'eval'. Here's a simplified example:

f1 <- function(x, q) eval(substitute(q), envir=x)
f2 <- function(x, q) f1(x, q)

What's happening:

> x <- data.frame(a=1:5)
> f1(x, a<3)
[1]  TRUE  TRUE FALSE FALSE FALSE
> f2(x, a<3)
Error in eval(expr, envir, enclos) : object 'a' not found

While I would like f2 to produce the same output like f1. Argument 'q' is some general query that is going to be evaluated on 'x'. I keep the example simple and general but I want to extend it's behavior on more complicated functions and queries. The thing that matters to me is how to "pass" the query "q" so that eval knows what to do with it no matter how many levels of nested functions there were before.

How can I do that? Thanks!

Upvotes: 1

Views: 228

Answers (2)

flodel
flodel

Reputation: 89097

You can do:

f1 <- function(x, q) eval(substitute(q), envir=x)
f2 <- function(x, q) eval(substitute(f1(x, q)))

y <- data.frame(a=1:5)
f1(y, a<3)
f2(y, a<3)

Upvotes: 2

JARO
JARO

Reputation: 249

Because you defined just x. You need:

> f2(x, x$a<3)
> [1]  TRUE  TRUE FALSE FALSE FALSE

Upvotes: 0

Related Questions