title: dplyr: Use a custom function in summarize() after group_by()
body: <p>How can we use a custom function after <code>group_by()</code>?
  I checked similar posts (<a href="https://stackoverflow.com/questions/24127237/custom-function-after-grouping-data-fame">1</a>, <a href="https://stackoverflow.com/questions/44730774/how-to-use-custom-functions-in-mutate-dplyr?rq=1">2</a>, and <a href="https://medium.com/optima-blog/writing-your-own-dplyr-functions-a1568720db0d" rel="noreferrer">3</a>), but my current code returns the same values for all groups.</p>
  
  <pre><code>&gt; data
     village     A     Z      Y 
       &lt;chr&gt; &lt;int&gt; &lt;int&gt;   &lt;dbl&gt; 
   1       a     1     1   500     
   2       a     1     1   400     
   3       a     1     0   800  
   4       b     1     0   300  
   5       b     1     1   700  
  
  z &lt;- 1
  data %&gt;%
      group_by(village) %&gt;%
      summarize(Y_village = Y_hat_village(., z))
  
  Y_hat_village &lt;- function(data_village, z){
      # Calculate the mean for a specific z in a village
      data_z &lt;- data_village %&gt;% filter(Z==get("z"))
      return(mean(data_z$Y))
  }
  </code></pre>
  
  <p>I want to have (500 + 400)/2 = 450 for village "a" and 700 for village "b".</p>