title: dplyr: passing a grouped tibble to a custom function
body: <p>(The following scenario simplifies my actual situation)<br>
  My data comes from villages, and I would like to summarize an outcome variable by a village variable.</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  
  </code></pre>
  
  <p>For example, I would like to calculate the mean of <code>Y</code> only using <code>Z==z</code> by villages. In this case, I want to have (500 + 400)/2 = 450 for village "a" and 700 for village "b". </p>
  
  <p>Please note that the actual situation is more complicated and I cannot directly use <a href="https://stackoverflow.com/questions/50925734/dplyr-use-a-custom-function-in-summarize-after-group-by/50926037?noredirect=1#comment88854293_50926037">this answer</a>, but <strong>the point is I need to pass a grouped tibble and a global variable (z) to my function</strong>.</p>
  
  <pre><code>z &lt;- 1 # z takes 0 or 1
  data %&gt;%
      group_by(village) %&gt;% # grouping by village
      summarize(Y_village = Y_hat_village(., z)) # pass a part of tibble and a global variable
  
  Y_hat_village &lt;- function(data_village, z){
      # This function takes a part of tibble (`data_village`) and a variable `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>However,  I found <code>.</code> passes entire tibble and the code above returns the same values for all groups.</p>