Re-order columns in Stata’s dtable

By default, if you use dtable to compare groups and include a "Total" column, the "Total" comes last. Here's how to re-order the columns.

. sysuse auto, clear (1978 automobile data)


. dtable i.rep78, by(foreign, tests)
note: using test pearson across levels of foreign for rep78.

-----------------------------------------------------------
                                  Car origin
                    Domestic    Foreign     Total     Test
-----------------------------------------------------------
N                  52 (70.3%) 22 (29.7%) 74 (100.0%)
Repair record 1978
  1                  2 (4.2%)   0 (0.0%)    2 (2.9%) <0.001
  2                 8 (16.7%)   0 (0.0%)   8 (11.6%)
  3                27 (56.2%)  3 (14.3%)  30 (43.5%)
  4                 9 (18.8%)  9 (42.9%)  18 (26.1%)
  5                  2 (4.2%)  9 (42.9%)  11 (15.9%)
-----------------------------------------------------------

The collect query autolevels command can be used to examine the current ordering of columns:

. collect query autolevels foreign

Automatic dimension levels
Collection: DTable
 Dimension: foreign
    Levels: 0 1 .m _dtable_test

Look at the "Levels:" line. We can use collect label list to check what those three values are:

. collect label list foreign

  Collection: DTable
   Dimension: foreign
       Label: Car origin
Level labels:
          .m  Total
           0  Domestic
           1  Foreign
_dtable_test  Test

So ".m" is the "Total" column and "_dtable_test" is the p-value. We can re-arrange it with collect style autolevels. We'll use the s(levels) macro, which currently contains the string "0 1 .m _dtable_test" from the "Levels:" line of the collect query autolevels foreign" output to avoid having to rewrite everything (duplicate entries, as .m will be, are apparently ignored), but we could of course manually order all columns.

. collect style autolevels foreign .m `s(levels)', clear

. collect query autolevels foreign

Automatic dimension levels
Collection: DTable
 Dimension: foreign
    Levels: .m 0 1 _dtable_test

. collect preview

-----------------------------------------------------------
                                  Car origin
                      Total     Domestic    Foreign   Test
-----------------------------------------------------------
N                  74 (100.0%) 52 (70.3%) 22 (29.7%)
Repair record 1978
  1                   2 (2.9%)   2 (4.2%)   0 (0.0%) <0.001
  2                  8 (11.6%)  8 (16.7%)   0 (0.0%)
  3                 30 (43.5%) 27 (56.2%)  3 (14.3%)
  4                 18 (26.1%)  9 (18.8%)  9 (42.9%)
  5                 11 (15.9%)   2 (4.2%)  9 (42.9%)
-----------------------------------------------------------

Primary source

Home | Back to blog

This work is licensed under CC BY-NC 4.0 Creative Commons BY-NC image