1

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!

2
  • Is the body of f2 the only thing you are willing to modify? Commented Oct 10, 2014 at 10:57
  • Sorry I'm not sure what you mean...? I can modify any of f1 or f2 functions, the only thing that matters is they both work the same with the same arguments where 'q' is some general query I want to evaluate on 'x'. Commented Oct 10, 2014 at 11:04

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

Because you defined just x. You need:

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

1 Comment

It is a simplified example. In general I would like the functions to do much more complicated stuff, so I want to pass the query 'q' as-is to the lower level function and evaluate it, so it does work the same in f1 and f2 with using the same arguments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.