<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/parameterizing-with-bquote/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.win-vector.com/blog/2018/09/parameterizing-with-bquote/"> R – Win-Vector Blog</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>One thing that is sure to get lost in my <a rel="nofollow" href="https://github.com/WinVector/wrapr/blob/master/extras/MacrosInR.md" target="_blank"><em>long</em> note on macros in <code>R</code></a> is just how concise and powerful macros are. The problem is macros are concise, but they do a lot for you. So you get bogged down when you explain the joke.</p>
<p>Let’s try to be concise.</p>
<p><span></span></p>
<p>
<p>Below is an extension of an example taken from the <a rel="nofollow" href="https://dplyr.tidyverse.org/articles/programming.html" target="_blank">Programming with <code>dplyr</code> note</a>.</p>
<p>First let’s load the package and define our symbols that hold names of columns we wish to work with later.</p>
<div>
<pre><code><span>suppressPackageStartupMessages</span>(<span>library</span>(<span>&quot;dplyr&quot;</span>))

group_nm &lt;-<span> </span><span>as.name</span>(<span>&quot;am&quot;</span>)
num_nm &lt;-<span> </span><span>as.name</span>(<span>&quot;hp&quot;</span>)
den_nm &lt;-<span> </span><span>as.name</span>(<span>&quot;cyl&quot;</span>)
derived_nm &lt;-<span> </span><span>as.name</span>(<span>paste0</span>(num_nm, <span>&quot;_per_&quot;</span>, den_nm))
mean_nm &lt;-<span> </span><span>as.name</span>(<span>paste0</span>(<span>&quot;mean_&quot;</span>, derived_nm))
count_nm &lt;-<span> </span><span>as.name</span>(<span>&quot;count&quot;</span>)</code></pre>
</div>
<p>Now let’s use <code>rlang</code> to substitute those symbols into a non-trivial <code>dplyr</code> pipeline.</p>
<div>
<pre><code>mtcars <span>%>%</span>
<span> </span><span>group_by</span>(<span>!!</span>group_nm) <span>%>%</span>
<span> </span><span>mutate</span>(<span>!!</span>derived_nm <span>:</span><span>=</span><span> </span><span>!!</span>num_nm<span>/!!</span>den_nm) <span>%>%</span>
<span> </span><span>summarize</span>(
    <span>!!</span>mean_nm <span>:</span><span>=</span><span> </span><span>mean</span>(<span>!!</span>derived_nm),
    <span>!!</span>count_nm <span>:</span><span>=</span><span> </span><span>n</span>()
  ) <span>%>%</span>
<span> </span><span>ungroup</span>() <span>%>%</span>
<span> </span><span>arrange</span>(<span>!!</span>group_nm)</code></pre>
</div>
<pre><code>## # A tibble: 2 x 3
##      am mean_hp_per_cyl count
##   </code></pre>