*! version 5.0 Mattia Chiapello 19nov2018

Title

balancetable -- Build a balance table (showing means and difference in means) and print it in a LaTeX file or an Excel file

Table of contents

Syntax

Description

Options

Remarks

Examples

Syntax

Basic syntax

balancetable varname depvarlist using filename [if] [in] [weight] [, options]

where varname must be a variable taking values 0 and 1 only.

Long syntax

balancetable (column1) [(column2) ...] depvarlist using filename [if] [in] [weight] [, options]

where (column#) can take either of these two forms:

a. (mean [if]), or

b. (diff varname [if]), where varname must be a variable taking values 0 and 1 only.

The long syntax can be used to show the means over several subsamples and/or when there is more than one treatment arm (see remarks below).

For both syntaxes, filename must be a LaTeX file (.tex) or an Excel file (.xls or .xlsx), and it can be preceded by the file path.

Content
pvalues print p-values instead of standard errors for the difference in means

vce(vcetype) specify the type of standard errors reported

fe(varname) add fixed effects when computing the difference in means

covariates(varlist) add control variables when computing the difference in means

stddiff compute standardized differences [basic syntax only]

observationscolumn add an additional column with the sample size for each variable in depvarlist [basic syntax only]

Table formatting and labels
wide[(statlist[, subopt])] make table wide, with statistics side by side

oneline[(stat[, subopt])] print only one row per variable

ctitles(strlist) insert column titles (in quotes)

leftctitle(string) change the title in the leftmost column of the title row

leftcobservations(string) change the text in the leftmost column of the footer

varnames use variable names in the balance table

varlabels use variable labels in the balance table

wrap[(opt)] wrap variable label if it is too long

# number of characters before wrapping

indent indent the second line

nonumbers do not print column numbers in the header

noobservations do not print the number of observations for each subsample in the footer

nolines do not print horizontal lines

groups(strlist[, subopt)] define and label groups of columns

pattern(numlist) define how to group columns

leftc(string) insert text in the leftmost column of the group row

prefix(string) define prefix to be added before each group label

suffix(string) define suffix to be added after each group label

begin(string) define common text to be added at the beginning of the group row [LaTeX only]

end(string) define common text to be added at the end of the group row [LaTeX only]

nomerge do not merge cells containing group labels [Excel only]

nohead omit entire table header

nofoot omit entire table footer

Cell formatting
format(fmt) format numbers inside the table

displayformat use display format in the table

nopar do not print parentheses around standard deviation and standard errors (or p-values)

par(l r) redefine the parentheses to be used

statistic(opt) apply formatting to each type of statistic

fmt(fmt) format numbers for specified statistic

nopar do not print parentheses around specified statistic

par(l r) redefine parentheses around specified statistic

Significance stars
nostars do not add significance stars

starlevels(levelslist) specify significance levels and symbols

staraux attach significance stars to standard errors (or p-values) instead of coefficients

LaTeX-specific
tabulary[(width)] use the tabulary environment in LaTeX

longtable use the longtable environment in LaTeX

booktabs use the booktabs package in LaTeX

prehead(strlist) add text before the table header

posthead(strlist) add text after the table header

prefoot(strlist) add text before the table footer

postfoot(strlist) add text after the table footer

varwidth(#) set maximum length of variable label

Output
replace overwrite existing file

append append to existing file [LaTeX only]

modify modify existing file [Excel only]

sheet(sheetname) write to worksheet sheetname [Excel only]

cell(cellreference) start printing table from cellreference [Excel only]

nomata do not use Mata in managing the output file [Excel only]

aweights, fweights and iweights are allowed; see weight.

Description

This command builds a balance table, comparing two or more subsamples according to a set of characteristics, with the goal of checking whether the differences are statistically significant. The
characteristics to be compared are listed in depvarlist, while varname is the dummy identifying the two subsamples.

The basic syntax can be used to illustrate the functioning of this command. For
each variable in depvarlist, balancetable does the following:

1. compute the mean and the standard deviation of the variable when varname is equal to 0, placing them in column (1);

2. compute the mean and the standard deviation of the variable when varname is equal to 1, placing them in column (2);

3. regress the variable in depvarlist on varname to compute the difference and the associated standard error (or p-value, if the appropriate option is specified), placing them in column (3).

The same procedure is applied to all the variables in depvarlist, to produce the complete balance table.

In step 3, it is possible to use different types of standard errors, add fixed effects or other control variables. In
addition, with balancetable it is possible to change the level of significance, set the numeric format and customize the table in many other ways.

The long syntax allows more control over the content of each column. In
particular, the user can add as many columns as desired, and these can be of two types:

a. type (mean), containing the mean and the standard deviation of each variable in depvarlist, as in columns (1) and (2) with the basic syntax;

b. type (diff), containing the difference between the subsamples indicated by varname, as well as the associated standard error (or p-value), as in column (3) with the basic syntax.

Options

Contents

Content

Table formatting and labels

Cell formatting

Significance stars

LaTeX-specific

Output

Content

pvalues instructs balancetable to print p-values instead of standard errors in column (3) for the basic syntax or in diff type columns for the complex syntax.

vce(vcetype) specifies the type of standard errors to be used. It
accepts all the standard errors used accepted by regress, but they must be specified inside the parentheses of vce(). For
instance, one could use vce(robust) or vce(cluster clustvar). This
option can be used in conjunction with pvalues: reported p-values are the correct ones.

fe(varname) includes fixed effects for varname when computing the coefficient in column (3). Of
course, if the fe() option is specified, the number in column (3) will no longer be the difference between column (1) and column (2).

The fe() option is outdated: it accepts only one variable; to add more fixed effects use the covariates() option.

covariates(varlist) includes covariates in varlist when computing the coefficient in column (3). Of
course, if the covariates() option is specified, the number in column (3) will no longer be the difference between column (1) and column (2).

The option covariates() accepts time-series operators and factor variables. Therefore,
it can be used to add fixed effects instead of using the fe() option (e.g. by typing cov(i.strata)).

stddiff computes the standardized differences in means and adds them in a column next to column (3). The
standardized difference is computed as [mean(t)-mean(c)]/[sqrt(var(t)+var(c))],
where mean(t) and mean(c) are the mean of the variable of interest in the treatment group and control group respectively, while var(t) and var(c) are the variances in those two groups.

observationscolumn adds one more column, containing the sample size for each regression computed in column (3). This
number may vary across variables in depvarlist, depending on the number of missing values for each variable.

Table formatting and labels

wide changes the table layout, so that statistics are shown side by side, taking one row in the table instead of two.

In addition, wide allows the user to optionally specify which statistics should be included in the table (the default is to include all). The
possible arguments of statlist are:

- mean: mean, first line of columns (1) and (2) (basic syntax) or mean type columns (complex syntax)

- sd: standard deviation, second line of columns (1) and (2) (basic syntax) or mean type columns (complex syntax)

- diff: difference in means, first line of column (3) (basic syntax) or diff type columns (complex syntax)

- se: standard error of the difference in means, second line of column (3) (basic syntax) or diff type columns (complex syntax)

- pval: p-value of the difference in means, second line of column (3) (basic syntax) or diff type columns (complex syntax)

Statistics specified in statlist by the user will be printed, regardless of the column where they are. For
instance, typing wide(mean diff se) will not print standard deviations and place mean of control group in the first column, mean of treatment group in the second,
difference in means in the third and standard error in the fourth.

wrapok makes wide compatible with the wrap option. By
default, these two options cannot be used together, because the second line of the variable label would be lost. By
specifying wrapok the user explicitly declares that it is ok to truncate long variable labels with the wrap option.

See remarks for more details on wide tables.

oneline drops the second line of the table for each variable (i.e. it only prints means and difference in means, and not standard deviations and standard errors/p-values).

It is possible to specify a stat, which can be either se or pval, to substitute the difference in means with standard errors or p-values respectively. Typing
oneline(se) -or oneline(pval)- ensures that column (3) (with the basic syntax) or the diff type columns (with the complex syntax) show the standard errors
-or the p-values- instead of showing the difference in means.

wrapok makes oneline compatible with the wrap option. The
rationale is the same as with the wide option.

See remarks for more details on one-line (wide) tables.

ctitles(strlist) is used to insert the titles of columns (1), (2), etc. Each
column title must be enclosed in quotes if it contains more than one word. The
titles will appear in the same order as they are written; to skip the title for one column, it is sufficient to open and close the quotes without any text in between ("") and then continue with the subsequent column title.

leftctitle(string) changes the title of the leftmost column, the one containing the variable names or labels (the default column name is "Variable"). The syntax to use to leave it empty is leftctitle(none). This
option is effective only if the option ctitles has been specified.

leftcobservations(string) changes the text of the leftmost column in the observations row (the default is "Observations"). This
option is effective only if noobservations has not been specified.

varnames includes variable names in the balance table (this is the default).

varlabels includes variable labels in the balance table, instead of variable names.

wrap split labels in two lines when they are too long. The
default is to wrap after 32 characters (unless a number is specified in the suboption), but words are not broken. Even
with the option wrap, labels can never take more than two lines.

# sets the number of characters after which the label is wrapped (the default is 32 characters).

indent ensures that the second line is indented, to ease readability.

nonumbers removes column numbers, i.e. (1), (2), etc. (included by default as the first row in the header).

noobservations removes the row with the number of observations for each subsample (added by default at the bottom of the table).

nolines removes the horizontal lines separating the header and the footer.

groups(strlist) defines and labels groups of columns, according to the scheme specified in pattern(). The
argument strlist is the list of labels in the order they should appear in the table. When
a label includes two or more words, it should be enclosed in quotes. If
the user specifies less labels than the number of models, the last labels will be assumed to be empty. If
there are more labels than groups, the extra labels are ignored.

pattern(numlist) defines how columns are allocated to groups. numlist
should be a list of 1s and 0s, where 1s indicate where groups start. For
instance, pattern(1 0 1) would indicate to group the first and the second column, while leaving the third column in a separate group. If
numlist has less elements than the number of columns, the last ones are assumed to be 0s. If
numlist has more elements than the number of columns, the extra ones are ignored. If
a pattern is not specified at all, balancetable assumes that all the columns belong to one big group, basically adding one extra title row in the header.

leftc(string) allows adding a text in the leftmost column (above the "Variable" title).

prefix(string) adds a prefix that is inserted before the label of each group.

suffix(string) adds a suffix that is inserted after the label of each group.

begin(string) adds a common beginning that is added before the entire group row. This
suboption is allowed only for LaTeX output files.

end(string) adds a common ending that is added after the entire group row. This
suboption is allowed only for LaTeX output files.

nomerge prevents balancetable from merging the cells forming each group, in Excel files (while with LaTeX files this option is not allowed). With
nomerge, group labels will still appear centered, but they will be stored in the first cell of the group, because the underlying cells have not been merged.

To merge cells, balancetable needs to use Mata. For
this reason, the option nomata (see below) automatically triggers the groups() suboption nomerge.

There are placehoders that can be used anywhere in the group() option (including in the label itself). Each
placeholder will be substituted with the appropriate number (see remarks below).

By default, when the output is a LaTeX file, prefix() will be "\multicolumn{@span}{" and suffix() "}",
so that the group labels are automatically placed in a centered multicolumn. Specifying
prefix() or suffix() will overwrite these.

nohead removes the table header. A
similar result would be achieved by specifying neither ctitles() nor group(), and using the options nonumbers and nolines. In
addition, for LaTeX output nohead also removes the initial "\begin...", as if the user specified prehead(""). Even
with nohead, the LaTeX-specific options prehead() and posthead() will still be usable.

nofoot removes the table footer. A
similar result would be achieved by using the options noobservations and nolines. In
addition, for LaTeX output nofoot also removes the final "\end", as if the user specified postfoot(""). Even
with nofoot, the LaTeX-specific options prefoot() and postfoot() will still be usable.

Cell formatting

These options allow controlling the format of the numbers used in the table and the parentheses used.

The statistic-specific options (indicated as statistic(opt) in the table above) override the generic options, both for numeric formats and for parentheses. For
numeric formats, displayformat overrides format().

format(fmt) allows formatting numbers inside the table according to conventional Stata formatting (e.g. %#.#g, %#.#fc, etc.).

displayformat uses the display format of each variable, instead of using a common format. This
may be useful when the balance table contains variables with very different magnitude. For
instance, the user may want to display large monetary amounts with commas and no decimal digits and dummy variables with 3 decimal digits. This
can be achieved by setting the appropriate format with the format command before creating the balance table and then using displayformat (see example below).

This option overrides format(). However,
it does not affect p-values, whose format can still be controlled with the generic format() option or with pval(fmt()).

nopar avoids printing parentheses around standard deviations and standard errors (or p-values).

par(l r) overrides the standard parentheses that are used in the table, which are ( and ) by default. For
instance, specifying par([ ]) inserts square brackets instead of parentheses.

Normally, par() requires two arguments. If,
for any reason, the user wants one-sided parentheses, this can be achieved by typing par(( "") or par("" ]).

mean, sd, diff, se, pval, stddiff, obs allow setting numeric format and parentheses for each type of statistic. They
actually are 7 separate options which follow the same syntax, but can be used independently to control each statistic. The
statistics are:

- mean: mean, first line of columns (1) and (2) (basic syntax) or mean type columns (complex syntax)

- sd: standard deviation, second line of columns (1) and (2) (basic syntax) or mean type columns (complex syntax)

- diff: difference in means, first line of column (3) (basic syntax) or diff type columns (complex syntax)

- se: standard error of the difference in means, second line of column (3) (basic syntax) or diff type columns (complex syntax)

- pval: p-value of the difference in means, second line of column (3) (basic syntax) or diff type columns (complex syntax) if pvalues is specified

- stddiff: standardized difference in means, first line of column (4) (basic syntax) if stddiff is specified

- obs: number of observations, last table row if noobservations is not specified and rightmost column if observationscolumn is specified (both controlled at the same time)

fmt(fmt) allows formatting numbers for the specified statistic according to conventional Stata formatting (e.g. %#.#g, %#.#fc, etc.).

nopar avoids printing parentheses around the specified statistic.

par(l r) specifies which parentheses to use for the specified statistic. It
follows the same rules as the generic par() option.

As mentioned above, each statistic has can be controlled independently. For
instance, ... , sd(nopar) se(par([ ])) will remove parentheses around the standard deviations and use square brackets around standard errors.

The option obs is somewhat different, as it controls two separate "areas" of the table. An
observation count is displayed at the bottom of the table, but also in the last column, with the observationscolumn option. Specifying
something like obs(fmt(%9.0f)) will affect both, it is not possible to control these two areas independently.

Statistic-specific options override generic options set for the whole table. For
instance, writing pvalues format(%12.0fc) pval(fmt(%5.3f)) will make sure that every number in the table is rounded to the nearest integer, except for p-values, which are shown with 3 decimal digits.

Significance stars

nostars drops the significance stars from the table. By
default, significance stars are added to column (3) with the basic syntax and to the diff type columns with the complex syntax.

starlevels(levelslist) allows defining the thresholds for significance and the corresponding symbols. Significance
levels can take values in the interval (0,1] and they must be written in descreasing order, followed by their symbol. That
is, levelslist should be something like ++ 0.01 +++ 0.005. The
default levels are * for p < 0.10, ** for p < 0.05 and *** for p < 0.01.

staraux shifts stars to the second line of the table (or to the next column for the wide table), so that they are attached to the standard errors (or p-values) instead of the coefficient.

LaTeX-specific

These options apply only if the output is a LaTeX file, that is the filename specified by the user has the .tex extension.

Options prehead(), posthead(), prefoot() and postfoot() should be compatible with the tabular environment, so the text must be chosen accordingly, i.e. using the correct number of "&" symbols and/or multicolumns, as well as "\\" at the end of each row. Also,
the total number of columns may increase to 5 or 6 when the options stddiff and/or observationscolumn are specified with the basic syntax,
while with the complex syntax the total number of columns depends on the number of parentheses.

tabulary prints the table using the tabulary environment in LaTeX (instead of the default tabular). This
allows for better spacing and text wrapping and it is particularly useful when column titles are rather long. It
is also possible to specify the width of the table. If
width is not entered by the user, it defaults to "\textwidth".

This option requires using the tabulary package in the .tex file and it cannot be used with longtable.

longtable allows building tables that span more than one page, with the longtable environment in LaTeX (instead of the default tabular). It
is useful if the balance table contains a large number of variables and therefore does not fit in one page.

This option requires using the longtable package in the .tex file and it cannot be used with tabulary.

booktabs uses the horizontal lines provided with the booktabs package, which allows for enhanced quality of tables. By
default, balancetable uses the standard "\hline" command in LaTeX.

This option requires using the booktabs package in the .tex file.

prehead(strlist) insert strings of text before the table header. The
text must be enclosed in quotes, and multiple quotes may be used to add several lines to the table. This
option allows the use of placeholders (see remarks below). By
default, prehead() contains the "\begin..." code and the top horizontal line of the table. Specifying
prehead() will overwrite it.

posthead(strlist) insert strings of text after the table header. The
text must be enclosed in quotes, and multiple quotes may be used to add several lines to the table. This
option allows the use of placeholders (see remarks below). By
default, posthead() contains the horizontal line separating the header from the main body of the table. Specifying
posthead() will overwrite it.

prefoot(strlist) insert strings of text before the table footer. The
text must be enclosed in quotes, and multiple quotes may be used to add several lines to the table. This
option allows the use of placeholders (see remarks below). By
default, prefoot() contains the horizontal line separating the main body of the table from the footer. Specifying
prefoot() will overwrite it.

postfoot(strlist) insert strings of text after the table footer. The
text must be enclosed in quotes, and multiple quotes may be used to add several lines to the table. This
option allows the use of placeholders (see remarks below). By
default, postfoot() contains the bottom horizontal line of the table and the "\end" code. Specifying
postfoot() will overwrite it.

varwidth(#) sets the length of the leftmost column of the table (the one with variable names or labels). This
width can be seen as expressed in number of characters, but in reality it is expressed in ex units, whose length depends on the font used. Basically,
varwidth creates a filler in each cell of the variable name/label column, stretching it to the desired width.

It would be safer not to use this option, it is provided mainly for backward compatibility. When
there is the need to set a specific width for the leftmost column, a better approach is to use a p column, replacing the head with a the prehead() option. For
instance, typing prehead("\begin

" "\toprule") would set the leftmost column to 5cm.

Output

replace allows overwriting filename if it already exists.

append makes sure that the newly created balance table is appended to the specified file if it already exists. This
option is valid only for LaTeX output files.

modify allows modifying an Excel file if it already exists. This
option is valid only for Excel output files.

sheet(sheetname) specifies that the table should be written in worksheet sheetname. If
this option is not specified, the balance table is placed in the first worksheet of the destination file. This
option is valid only for Excel output files.

cell(cellreference) specifies that the table should be printed using cellreference as the upper-left corner. If
this option is not specified, the balance table will start from the first cell of the worksheet (cell A1). This
option is valid only for Excel output files.

nomata prevents balancetable from using Mata to manage the output file. Mata
is used when merging cells for the groups() option and when processing the cell() option. Should
these steps cause any problems, nomata offers a workaround; however, this should be avoided, if possible. This
option is valid only for Excel output files.

Remarks

Contents

Long syntax

Wide table

Placeholders

Quotes

Long syntax

The long syntax allows a more refined control over the table layout, by letting the user specify the content of each column inside the parentheses. The
long syntax supports two types of columns (mean and diff), mimicking those used in the basic syntax.

The mean column takes the form

(mean [if])

allowing the use of an optional if expression to identify the subsample over which to calculate the mean and the standard deviations.

The diff column takes the form

(diff varname [if])

meaning that it requires specifying a varname (which must be binary) to identify the two subsamples to calculate the difference and the standard errors (and it also supports optional if expressions).

Therefore, the short syntax

. balancetable treatvar depvar_1 depvar_2 depvar_3 using "myfile.tex"

is completely equivalent to

. balancetable (mean if treatvar==0) (mean if treatvar==1) (diff treatvar) depvar_1 depvar_2 depvar_3 using "myfile.tex"

The long syntax is especially useful in case of multiple treatments. For
instance, suppose we have an experiment with two treatment arms (A and B) and a control group, and we want to check the balance of each treatment arm versus the control group and the balance between treatment arms.

We could write

. balancetable (mean if treatment==0) (mean if treatment==1) (mean if treatment==2) (diff treatment_A if treatment!=2) (diff treatment_B if treatment!=1) (diff treatment_A if treatment!=0) $depvarlist using "myfile.xls"

where treatment is a variable that takes value 0 for the control group, value 1 for treatment A and value 2 for treatment B, while treatment_A and treatment_B are two dummy variables for treatment arms.

As mentioned above, (diff) type columns require the use of a binary (dummy) variable, and the command balancetable does not create them. In
the previous example, treatment_A and treatment_B must be created by the user, for instance in the following way:

. generate treatment_A = (treatment==1)

. generate treatment_B = (treatment==2)

One final remark: if expressions placed inside the parentheses are complementary to the [if] [in] conditions specified in the main argument of balancetable,
that is both are applied to the relevant columns (see example below).

Wide table

Usually, balancetable would produce a table with twice as many rows as variables in the depvarlist. For
each variable, the first row contains means and difference in means, while the second row contains standars deviations and standard errors (or p-values).

With the wide option, however, the table is reshaped so that the statistics that would normally be on the second row are placed next to the ones of the first row. Therefore,
the number of columns of the table doubles, while the rows are as many as the variables in the depvarlist.

The oneline option follows a similar procedure, producing a table with one row per variable, but without doubling the number of columns.

Since the wide table only has one line per variable, it is incompatible with the wrap option. An
exception is made if the user specifies the wrapok suboption, accepting that variable labels are truncated according to the parameters of the wrap options,
with the consequent loss of the second part of the label.

Also oneline accepts the wrapok suboption, even when there is no main option. The
syntax in this case is simply oneline(, wrapok).

By default, wide includes all the statistics in the table. However,
it is possible to control which statistics to include by adding an optional statlist. If
statlist is specified, only the columns with the selected statistics will be included in the table.

The statistics that can be included in statlist are the following:

- mean: mean, first line of columns (1) and (2) (basic syntax) or mean type columns (complex syntax)

- sd: standard deviation, second line of columns (1) and (2) (basic syntax) or mean type columns (complex syntax)

- diff: difference in means, first line of column (3) (basic syntax) or diff type columns (complex syntax)

- se: standard error of the difference in means, second line of column (3) (basic syntax) or diff type columns (complex syntax)

- pval: p-value of the difference in means, second line of column (3) (basic syntax) or diff type columns (complex syntax)

With the basic syntax, two more statistics can be displayed: the standardized difference and the number of observations used in the regression. These
are always included when wide is specified, if they have been computed. If
they are not meant to be in the table, they should not be added in the first place, by not using the stddiff or observationscolumn options.

The order in which statistics appear in statlist does not matter, it will not change the order in the final table.

By default, if one of the above is specified, all the statistics of that type will be included in the table. For
instance, if you specify wide(mean sd diff), the table will not contain the standard errors, but it will include all means, all standars deviations and all differences in means.

Actually, statlist allows an even more granular control of the columns to include in the table. The
user can specify exactly the column from which each statistic must be printed, by adding the column number. For
instance, typing wide(mean1 sd1 sd2 diff) will drop the column containing the mean of the second subsample (corresponding to mean2),
in addition to dropping the standard errors.

The number to be added to the statistic is the column where the statistic would have been if the table had not been wide. That
is, it is the number of the parenthesis in the complex syntax. As
a result, the following three syntaxes are perfectly equivalent:

. balancetable ... , wide

. balancetable ... , wide(mean sd diff se)

. balancetable ... , wide(mean1 sd1 mean2 sd2 mean3 sd3 diff4 se4)

The option oneline drops the second row for each variable of depvarlist, keeping only means and differences in means. Basically,
specifying oneline is exactly the same as writing wide(mean diff).

There is also the possibility of replacing the differences in means with the standard errors or the p-values, using the alternative options se or pval. In
this case, oneline(se) is the same as wide(mean se).

A short remark on wide/one-line tables: to specify wide(pval) or oneline(pval), they must be combined with the pvalues option of the balancetable command.

The option wide can be used to create very non-standard balance tables. For
instance, consider a table created with oneline(se), showing means in columns (1) and (2), and standard errors in column (3). If,
for any reason, someone wanted to show standard deviations instead of means, this could be achieved by typing

. balancetable ... , wide(sd se)

Placeholders

There are placehoders that can be used with the options groups() (in the label itself or in its suboptions), prehead(), posthead(), prefoot() and postfoot(). These
placeholders will be substituted with the appropriate numbers before printing the table.

The available placeholders are the following:

- @span: number of columns spanned by the current group (available only for the groups() option)

- @col: number of columns in with a statistic in the table (e.g. 3 with the basic syntax, or 6 with the basic syntax and the wide option)

- @tot: total number of columns, including the leftmost column with variable names/labels (that is, @tot=@col+1)

As an example, a placeholder could be used in the prehead() to change the tabular environment and align to the right the columns of the main body of the table (while keeping the column with variable names aligned to the left). The
syntax would be the following:

. balancetable treatment depvar_1 depvar_2 using "file.tex", prehead("\begin" "\hline")

Or a placeholder could be used with the groups() option to create horizontal lines spanning columns (1)-(4), with a code like this:

. balancetable treatment depvar_1 depvar_2 using "file.tex", observationscolumn groups("Title", end("\cmidrule{2-@tot}"))

This way, the table will correctly contain "\cmidrule{2-5}" (the option observationscolumn adds one column, so the table has 5 columns in total).

Quotes

It is almost always possible to use quotation marks inside titles and labels, if using the correct syntax.

As a general rule, whenever an option in the table above mentions string as an argument, it is expected to receive only one string. For
this reason, any outer quotes are stripped away (that is, writing leftc("text") or leftc(text) is perfectly equivalent). In
order to add quotation marks to the text, it is necessary to use Stata's compound double quotes.

Options behaving in this way are leftctitle(), leftcobservations(), tabulary() and all the suboptions of groups()
(specifically, left(), prefix(), suffix(), begin() and end()). Also
cell() and sheet() can be written with or without quotes, but sheet() does not accept compound double quotes.

On the other hand, options that take strlist as an argument expect a list of strings. Each
one of these strings must be contained in quotes (unless it is a one-word string, making quotes unnecessary). Also
in this case it is possible to print text with quotation marks, by enclosing the corresponding string in compound double quotes.

The main examples are ctitles() and the main argument of groups(). List of strings are accepted also by prehead(),
posthead(), prefoot() and postfoot(); with these options, each string will be printed in a separate line of the .tex file.

Check the example below to see how quotes can be used.

Examples

These examples are not meant to show correct practices to build a balance table or the specifications to use. They
are just meant to show how the options of balancetables can be used and combined.

Basic syntax with column titles

. balancetable subsample_dummy age sex income using "myfile.tex", ctitles("Control group" "Treatment group" "Difference")

Basic syntax computing robust standard errors and showing the corresponding p-values, in a tabulary environment

. balancetable choice_dummy var1 var2 var3 var4 using "path/myfile.tex", vce(robust) pval ctitles("First group" "Second group" "Difference") tabulary

Subsample and weights, with prefoot

. balancetable dummy var1 var2 var3 var4 using "myfile.tex" if baseline==1 [iweight=myweightvar], prefoot(" & This goes in column (1) & & This goes in column (3) \\")

Standardized differences column and postfoot to add table notes

. balancetable dummy var1 var2 var3 var4 using "My file.tex", stddiff ///

postfoot("\hline" "\multicolumn{5} \\" `"\multicolumn{5}{"notes" may have quotes, requiring compound quotes in postfoot} \\"'' "\end")

Use of variable labels and label wrapping

. balancetable treatment covariate1 covariate2 covariate3 using "filename.tex", varlabels wrap(15 indent)

File path including directory and replace option

. balancetable treatment_dummy age sex income using "mydirectory/somefile.xlsx", replace

Complex syntax with 2 treatment arms and 1 control group

. generate treat_A = (treat==1)

. generate treat_B = (treat==2)

. balancetable (mean if treat==0) (mean if treat==1) (mean if treat==2) (diff treat_A if treat!=2) (diff treat_B if treat!=1) (diff treat_A if treat!=0) $depvarlist using "myfile.xlsx", ///

ctitles("Mean Control" "Mean treat. A" "Mean treat. B" "Treat. A vs Control" "Treat. B vs Control" "Treat. A vs Treat. B")

. drop treat_A treat_B

Complex syntax (mimicking basic syntax) restricting to a subsample (if condition), without numbers row and with booktabs style

. balancetable (mean if treat==0) (mean if treat==1) (diff treat) age sex income hh_members using "balance.tex" if followup1==1, nonumbers booktabs

Clustered standard errors and factor variables as covariates (fixed effects)

. balancetable treatment age sex income years_education using "bt.xls", vce(cluster village) covariates(i.survey_wave i.village)

One-line table, without parentheses, showing p-values and with custom confidence levels

. balancetable treatment age sex income years_education using "bt.tex", pvalues oneline(pval) nopar starlevels(+ 0.1 ++ 0.05)

Wide table without difference in means and with (starred) p-values

. balancetable treat $depvarlist using "file.xlsx", wide(mean sd pval) pvalues staraux ///

ctitles("Mean control" "SD control" "Mean treat" "SD treat" "P-val. control vs treat")

Wide table showing differences and standard errors and then subsample means (not showing standard deviations), format with one decimal digit

. balancetable (diff treat) (mean if treat==0) (mean if treat==1) $depvars using "Output file.tex", wide(mean diff se) format(%9.1f)

Column groups with booktabs style and lines under group labels

. balancetable dummy $depvarlist using "file.tex", booktabs ctitles("Control" "Treatment" "Control vs Treatment") ///

groups("Means" "Difference", pattern(1 0 1) end("\cmidrule(lr){2-3} \cmidrule(lr){4-4}"))

Table with statistics for full sample, subsample A, subsample B and difference, and with column groups

. balancetable (mean) (mean if dummy==1) (mean if dummy==0) (diff dummy) dep1 dep2 dep3 dep4 using "bt.tex", ///

groups("Means" "Difference", pattern(1 0 0 1) leftc("Stat.")) ///

ctit("Full sample" "Subsample A" "Subsample B" "A vs B") lefctit("Sample")

Minimally formatted table (no header, no footer, etc.)

. balancetable treat $variables using "myfile.xlsx", nohead nofoot nopar nostars noobs varnames

Format changing by variables (comma and no decimal digits for monetary amounts and 2 decimal digits for dummy variables) and show p-values with 3 decimal digits

. format $monetary_vars %10.0fc

. format $dummy_vars %4.2f

. balancetable treatment $monetary_var $dummy_vars using "anyfile.xlsx", displayformat format(%4.3f) pvalues

Two separate tables comparing control vs treatment 1 and control vs treatment 2, one per worksheet, starting from cell B2

. gen t1 = treat==1

. gen t2 = treat==2

. balancetable (mean if treat==0) (mean if treat==1) (diff t1 if treat!=2) $depvars using "Excel file.xlsx", replace sheet(First sheet) cell(B2) ///

ctitles("Mean control" "Mean treatment 1" "Diff. control vs treat. 1")

. balancetable (mean if treat==0) (mean if treat==2) (diff t2 if treat!=1) $depvars using "Excel file.xlsx", modify sheet(Second sheet) cell(B2) ///

ctitles("Mean control" "Mean treatment 2" "Diff. control vs treat. 2")

Compound double quotes

. balancetable dummy $depvarlist using "file.xls", replace wide sheet("Sheet name") cell(B2) ///

ctitles(First "Second column" `"Third "column" with quotes"' Fourth "Fifth column" "6th") leftctitle(No need for quotes here) ///

groups("First group" `"Second "group""' Third, pattern(1 0 1 0 1 0) leftc("These quotes here are unnecessary"))

Author

Mattia Chiapello, chiapello.ma@gmail.com

If you have been patient enough to read until here, congratulations!

Hopefully, the explanations and examples in this help file were useful. Should
this not be the case, feel free to send me an email and I will try to help.

You can also contact me if you find any errors or if there are any features that you would like to be added to balancetable: any feedback is more than welcome.