R: passing values to eval in nested functions

限于喜欢 提交于 2020-01-15 20:10:34

问题


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!


回答1:


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)



回答2:


Because you defined just x. You need:

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


来源:https://stackoverflow.com/questions/26297341/r-passing-values-to-eval-in-nested-functions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!