title: Use dplyr to group-by dataset and summarize mean and SD (standard deviation)
body: <p>I have some python code that uses <code>.groupby</code> and <code>.agg</code> to convert a dataframe into a summary table, and am having trouble converting into R. My desired output looks like this:</p>
  
  <p>Figure 1. Format for desired output
  <a href="https://i.stack.imgur.com/n3US5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n3US5.png" alt="enter image description here"></a></p>
  
  <p>Imagine that the starting dataframe <code>df</code> looks like this:</p>
  
  <pre><code>Y1  Y2  Y3   Sex    X1  X2   X3    X4     X5    X6
  1   0   1    Male   52  2    7.25  11.40  0.50  2
  0   0   0    Female 42  1    2.00  27.00  1.00  2
  1   0   1    Male   46  4    0.08  16.20  0.17  3
  0   0   0    Female 60  3    5.65  2.00   1.68  1
  1   0   1    Male   81  1    1.37  9.20   0.80  0
  0   0   0    Female 44  2    0.87  15.40  1.00  0
  1   0   1    Male   61  4    0.87  19.40  0.25  2
  0   0   0    Female 46  1    2.00  7.20   1.00  1
  1   0   1    Male   56  1    7.25  1.40   0.45  2
  0   0   0    Female 54  2    2.00  25.20  1.00  3
  </code></pre>
  
  <p>I want to be able to convert <code>df</code> to look like Figure 1 in R. So far I've figured out I can use the <code>dplyr</code> package to groupby and summarize a dataset:</p>
  
  <pre><code>df %&gt;%
    group_by(Sex) %&gt;%
    summarize(
    m = mean(X1, na.rm=TRUE),
    sd = sd(X1)
  ) 
  </code></pre>
  
  <p>However this only gives me the summary for the variable X1 and I need it to be grouped-by Y1, Y2, Y3 and the rest of the X variables.</p>
  
  <p>So how can I code this so it looks like Figure 1?</p>
  
  <p>FWIW, this is more or less the code I used in python but I need it for R.</p>
  
  <pre><code>Y1_ = df.groupby(['Y1','Sex']).agg(['mean','std']).round(2)
  Y2_ = df.groupby(['Y2','Sex']).agg(['mean','std']).round(2)
  Y3_ = df.groupby(['Y3','Sex']).agg(['mean','std']).round(2)
  
  frames = [Y1_, Y2_, Y3_]
  table1 = pd.concat(frames, keys=['Y1','Y2','Y3'], ignore_index=False)
  </code></pre>