如何编写用于评估数据框中的表达式的R函数 [英] How to write an R function that evaluates an expression within a data-frame

查看:51
本文介绍了如何编写用于评估数据框中的表达式的R函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

R认知难题:假设我们有一个数据框:

Puzzle for the R cognoscenti: Say we have a data-frame:

df <- data.frame( a = 1:5, b = 1:5 )

我知道我们可以做类似的事情

I know we can do things like

with(df, a)

获取结果向量.

但是我该如何编写一个接受表达式(例如aa > 3)并在内部执行相同操作的函数. IE.我想编写一个函数fn,该函数将一个数据框和一个表达式作为参数,并返回将表达式评估"在数据框内作为环境的结果.

But how do I write a function that takes an expression (such as a or a > 3) and does the same thing inside. I.e. I want to write a function fn that takes a data-frame and an expression as arguments and returns the result of evaluating the expression "within" the data-frame as an environment.

不要介意这听起来像是人为的(我可以如上所述使用with),但这只是我正在编写的更复杂函数的简化版本.我尝试了几种变体(使用evalwithenvirsubstitutelocal等),但是它们都不起作用.例如,如果我这样定义fn:

Never mind that this sounds contrived (I could just use with as above), but this is just a simplified version of a more complex function I am writing. I tried several variants ( using eval, with, envir, substitute, local, etc) but none of them work. For example if I define fn like so:

fn <- function(dat, expr) {
  eval(expr, envir = dat)
}

我收到此错误:

> fn( df, a )
Error in eval(expr, envir = dat) : object 'a' not found

很显然,我缺少有关环境和评估的细微之处.有没有定义这种功能的方法?

Clearly I am missing something subtle about environments and evaluation. Is there a way to define such a function?

推荐答案

lattice包以不同的方式来执行这种操作.参见例如lattice:::xyplot.formula.

The lattice package does this sort of thing in a different way. See, e.g., lattice:::xyplot.formula.

fn <- function(dat, expr) {
  eval(substitute(expr), dat)
}
fn(df, a)             # 1 2 3 4 5
fn(df, 2 * a + b)     # 3 6 9 12 15

这篇关于如何编写用于评估数据框中的表达式的R函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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