title: How can I export a two-way table?
body: <p>I have created a two-way summary table in Stata, but I am struggling to output my results. </p>
  
  <p>Using the <code>auto.dta</code> sample dataset as an example, I am trying to build a table that displays the means and standard deviations of <code>mpg</code>, by two other variables (<code>expensive</code> and <code>foreign</code>).</p>
  
  <p>My code currently looks as follows:</p>
  
  <pre><code>sysuse auto.dta, replace
  gen expensive = (price &gt; 5000)
  </code></pre>
  
  <p>The table that I would like to display can be created by either of the two commands below:</p>
  
  <pre><code>tabulate expensive foreign, sum(mpg)
  
         Means, Standard Deviations and Frequencies of Mileage (mpg)
  
             |      Car type
   expensive |  Domestic    Foreign |     Total
  -----------+----------------------+----------
           0 | 22.137931     28.875 | 23.594595
             | 4.3648281  4.8825491 | 5.2305696
             |        29          8 |        37
  -----------+----------------------+----------
           1 | 16.913043  22.428571 |        19
             | 3.4629604  6.4416229 | 5.4467115
             |        23         14 |        37
  -----------+----------------------+----------
       Total | 19.826923  24.772727 | 21.297297
             | 4.7432972  6.6111869 | 5.7855032
             |        52         22 |        74
  </code></pre>
  
  <p></p>
  
  <pre><code>table expensive foreign, c(mean mpg sd mpg) row col
  
      ----------------------------------------
                |           Car type          
      expensive | Domestic   Foreign     Total
      ----------+-----------------------------
              0 |  22.1379    28.875   23.5946
                | 4.364828  4.882549   5.23057
                |       29         8        37
                | 
              1 |   16.913   22.4286        19
                |  3.46296  6.441623  5.446712
                |       23        14        37
                | 
          Total |  19.8269   24.7727   21.2973
                | 4.743297  6.611187  5.785503
                |       52        22        74
      ----------------------------------------
  </code></pre>
  
  <p>I can also closely approximate the same results using <code>collapse</code>, but this does not calculate row and column totals.</p>
  
  <p>My issue is that neither the <code>tabulate</code> (with the <code>sum</code> option) command nor the <code>table</code> command seem friendly to output.  I have tried converting to matrices, but <code>tabulate</code> with the <code>sum</code> option does not allow the <code>matcell</code> option and <code>table</code> seems similarly uncooperative.</p>
  
  <p>I'm familiar with <code>tabstat</code>, <code>esttab</code> etc., but was not able to create the two-way table that I need with any of those packages.  Any help would be really appreciated.</p>