R:将值传递给嵌套函数中的eval [英] R: passing values to eval in nested functions

查看:68
本文介绍了R:将值传递给嵌套函数中的eval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一些查询传递给使用'eval'的较低级函数.这是一个简化的示例:

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)

发生了什么事

> 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

虽然我希望f2产生与f1相同的输出.参数"q"是一些通用查询,将在"x"上求值.我使该示例保持简单和通用,但我想将其行为扩展到更复杂的函数和查询上.对我而言,重要的是如何传递"查询"q",以便eval知道之前有多少层嵌套函数,该如何处理.

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.

我该怎么做?谢谢!

推荐答案

您可以这样做:

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)

这篇关于R:将值传递给嵌套函数中的eval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆