title: How to write an R function that evaluates an expression within a data-frame
body: <p>Puzzle for the R cognoscenti: Say we have a data-frame:</p>
  
  <pre><code>df &lt;- data.frame( a = 1:5, b = 1:5 )
  </code></pre>
  
  <p>I know we can do things like</p>
  
  <pre><code>with(df, a)
  </code></pre>
  
  <p>to get a vector of results. </p>
  
  <p>But how do I write a function that takes an expression (such as <code>a</code> or <code>a &gt; 3</code>) and does the same thing inside. I.e. I want to write a function <code>fn</code> 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. </p>
  
  <p>Never mind that this sounds contrived (I could just use <code>with</code> as above), but this is just a simplified version of a more complex function I am writing. I tried several variants ( using <code>eval</code>, <code>with</code>, <code>envir</code>, <code>substitute</code>, <code>local</code>, etc) but none of them work. For example if I define <code>fn</code> like so:</p>
  
  <pre><code>fn &lt;- function(dat, expr) {
    eval(expr, envir = dat)
  }
  </code></pre>
  
  <p>I get this error:</p>
  
  <pre><code>&gt; fn( df, a )
  Error in eval(expr, envir = dat) : object 'a' not found
  </code></pre>
  
  <p>Clearly I am missing something subtle about environments and evaluation. Is there a way to define such a function?</p>