title: dplyr: group over several variables in a function
body: <p>I want to have two lists of grouping variables. let's say <code>list1 = c(&quot;var2&quot;,&quot;var3&quot;,&quot;var4&quot;)</code> and   <code>list2 = c(&quot;var2&quot;,&quot;var3&quot;)</code></p>
  <pre><code>dta = data.frame(var1 = c(1:8),
                   var2 = c(rep(&quot;AA&quot;,4),rep(&quot;BB&quot;,4)),
                   var3 = rep(c(&quot;C&quot;,&quot;D&quot;),4),
                   var4 = c(1,1,0,0,0,0,1,1))
  
  dta %&gt;% group_by(var2,var3,var4) %&gt;% summarise(mv1 = mean(var1)) %&gt;% 
    group_by(var2,var3) %&gt;% summarise(mv1_2 = mean(mv1))
  </code></pre>
  <p>How can I create a function like this</p>
  <pre><code>sample_fun = function(dta, list1, list2){
  
      dta %&gt;% group_by(list1) %&gt;% summarise(mv1 = mean(var1)) %&gt;% 
    group_by(list2) %&gt;% summarise(mv1_2 = mean(mv1))
  
  }
  </code></pre>