title: How do I calculate a grouped z score in R using dplyr?
body: <p>Using the <code>iris</code> dataset I'm trying to calculate a z score for each of the variables. I have the data in tidy format, by performing the following:</p>
  
  <pre><code>library(reshape2)
  library(dplyr)
  test &lt;- iris
  test &lt;- melt(iris,id.vars = 'Species')
  </code></pre>
  
  <p>That gives me the following:</p>
  
  <pre><code>  Species     variable value
  1  setosa Sepal.Length   5.1
  2  setosa Sepal.Length   4.9
  3  setosa Sepal.Length   4.7
  4  setosa Sepal.Length   4.6
  5  setosa Sepal.Length   5.0
  6  setosa Sepal.Length   5.4
  </code></pre>
  
  <p>But when I try to create a z-score column for each group (e.g. the z-score for Sepal.Length will not be comparable to that of Sepal. Width) using the following:</p>
  
  <pre><code>test &lt;- test %&gt;% 
    group_by(Species, variable) %&gt;% 
    mutate(z_score = (value - mean(value)) / sd(value))
  </code></pre>
  
  <p>The resulting z-scores have not been grouped, and are based on all of the data. </p>
  
  <p>What's the best way to return the z-scores by group using dpylr?</p>
  
  <p>Many thanks! </p>