How can I use dplyr/magrittr's pipe inside functions in R?
<p>I'm trying to write a function which takes as argument a dataframe and the name of the function. When I try to write the function with the standard R syntax, I can get the good result using <code>eval</code> and <code>substitute</code> as recommanded by @hadley in <a href="http://adv-r.had.co.nz/Computing-on-the-language.html" rel="nofollow">http://adv-r.had.co.nz/Computing-on-the-language.html</a></p>

<pre><code>&gt; df &lt;- data.frame(y = 1:10)
&gt; f &lt;- function(data, x) {
+   out &lt;- mean(eval(expr = substitute(x), envir = data))
+   return(out)
+ }
&gt; f(data = df, x = y)
[1] 5.5
</code></pre>

<p>Now, when I try to write the same function using the <code>%&gt;%</code> operator, it doesn't work : </p>

<pre><code>&gt; df &lt;- data.frame(y = 1:10)
&gt; f &lt;- function(data, x) {
+   data %&gt;% 
+     eval(expr = substitute(x), envir = .) %&gt;% 
+     mean()
+ }
&gt; f(data = df, x = y)
Show Traceback
Rerun with Debug
 Error in eval(expr, envir, enclos) : objet 'y' introuvable 
&gt; 
</code></pre>

<p>How can I using the combine the piping operator with the use of <code>eval</code> and <code>substitute</code> ? It's seems really tricky for me.</p>