title: How can I use dplyr group_by within a function, conditional on a flag?
body: <p>I want to define a custom function which groups and summarises some data using dplyr, and conditional on a Boolean flag can group by an additional level. I can achieve this using a full if... else control block as in this trivial example:</p>
  <pre><code>library(tidyverse)
  data(Titanic)
  
  Titanic &lt;- as_tibble(Titanic)
  
  foo &lt;- function(by_age = FALSE) {
    if (by_age) {
      bar &lt;- Titanic %&gt;%
        group_by(Survived, Age)
    } else {
      bar &lt;- Titanic %&gt;%
        group_by(Survived)
    }
    
    bar %&gt;%
      summarise(n = sum(n))
  }
  
  foo()
  foo(by_age = TRUE)
  </code></pre>
  <p>But this seems a very clumsy way round. <strong>Is there a way I can achieve this with a single block of dplyr code, conditionally calling Age as a second grouping variable?</strong> I've tried with <code>ifelse(by_age, Age, NA)</code> in my <code>group_by</code> statement, and some of the techniques listed in <a href="https://stackoverflow.com/questions/21815060/dplyr-how-to-use-group-by-inside-a-function">this SO post</a> but to no avail.</p>