title: Using purrr and dplyr: is rlang::sym the best way
body: <p>I'd like to write functions that use dplyr verbs, which means I have to wade into the murky waters of <code>rlang</code>.</p>
  
  <p>To provide a concrete example, say I want to use <code>purrr::map_df()</code> to iterate over  variables in a <code>dplyr::group_by()</code>. The <a href="https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html" rel="nofollow noreferrer">programming with dplyr</a> vignette walks through writing a <code>my_summarise()</code> function; the approach there is to use <code>rlang::enquo()</code> on the grouping variable, then unquote with <code>!!</code>.
  This approach works to make a new dplyr-like function that takes unquoted variable names (<code>my_summarise(df, g1)</code> in the vignette).</p>
  
  <p>In contrast, I want to purrr provide the variable name as a string. Is <code>rlang::sym()</code> the right way to do this? It seems like it isn't, because <code>sym()</code> isn't mentioned in the dplyr programming vignette and barely mentioned in the rlang <a href="http://rlang.tidyverse.org/articles/tidy-evaluation.html" rel="nofollow noreferrer">tidy evaluation article</a>. Is there a better way?</p>
  
  <pre><code>library(tidyverse)
  my_summarise &lt;- function(df, group_var) {
    group_var &lt;- rlang::sym(group_var)
  
    df %&gt;%
      group_by(!!group_var) %&gt;%
      summarise(mpg = mean(mpg))
  }
  
  # This works. Is that a good thing?
  purrr::map_df(c("cyl", "am"), my_summarise, df = mtcars)
  
  # A tibble: 5 x 3
      cyl   mpg    am
    &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
  1  4.00  26.7 NA   
  2  6.00  19.7 NA   
  3  8.00  15.1 NA   
  4 NA     17.1  0   
  5 NA     24.4  1.00
  </code></pre>
  
  <p>As a follow-up, why does simply unquoting (without first applying <code>enquo</code> or <code>sym</code>) work some of the time?  In the example below, why does <code>select()</code> work as expected but <code>group_by()</code> doesn't? </p>
  
  <pre><code>x &lt;- "cyl"
  select(mtcars, !!x)
  group_by(mtcars, !!x)
  </code></pre>
  
  <p>Update: the answer is not about unquoting. It's that <code>select</code> is more flexible and can handle strings, while <code>group_by</code> can't.</p>
  
  <p>Other ref: This <a href="https://edwinth.github.io/blog/dplyr-recipes/" rel="nofollow noreferrer">blog post</a> by Edwin Thoen.</p>