#161: added nonumbers option to helpfile

{smcl}
{* 19 Oct 2018}{...}
{hline}
help for {hi:ieddtab}
{hline}

{title:Title}

{phang2}{cmdab:ieddtab} {hline 2} This command runs a Diff-in-Diff regression and displays the baseline values, the two 1st differences and the 2nd difference.

{phang2}For a more descriptive discussion on the intended usage and work flow of this
command please see the {browse "https://dimewiki.worldbank.org/wiki/ieddtab":DIME Wiki}.

{title:Syntax}

{phang2} {cmdab:ieddtab} {it:varlist} [{help if}] [{help in}] [{help weight}],
	{cmdab:t:ime(}{it:varname}{cmd:)} {cmdab:treat:ment(}{it:varname}{cmd:)}
		{break}[
		{cmdab:covar:iates(}{it:varlist}{cmd:)} {cmdab:starl:evels(}{it:numlist}{cmd:)}
		{cmdab:err:ortype(}{it:string}{cmd:)} {cmdab:rowl:abtype(}{it:string}{cmd:)}
		{cmdab:rowlabtext(}{it:label_string}{cmd:)} {cmdab:format(}{it:{help format:%fmt}}{cmd:)}
		{cmdab:replace} {cmdab:savet:ex(}{it:filepath}{cmd:)} {cmdab:onerow} {cmdab:nonumbers}
		{cmdab:nonotes} {cmdab:addn:otes(}{it:string}{cmd:)}  {cmdab:texdoc:ument}
		{cmdab:texc:aption(}{it:string}{cmd:)} {cmdab:texl:abel(}{it:string}{cmd:)}
		{cmdab:texn:otewidth(}{it:numlist}{cmd:)} {cmdab:texvspace(}{it:string}{cmd:)}
	]

{pmore}Where {it:varlist} is a list of numeric continuous outcome variables (also called dependent variables or left hand side variables) to be used in the difference-in-difference regression(s) this command runs and presents the results from.{p_end}

{marker opts}{...}
{synoptset 24}{...}
{synopthdr:options}
{synoptline}
{pstd}{it:Required options:}{p_end}
{synopt :{cmdab:t:ime(}{it:varname}{cmd:)}}Time dummy to use in diff-in-diff regression{p_end}
{synopt :{cmdab:treat:ment(}{it:varname}{cmd:)}}Treatment dummy to use in diff-in-diff regression{p_end}

{pstd}{it:Statistics options:}{p_end}
{synopt :{cmdab:covar:iates(}{it:varlist}{cmd:)}}Covariates to use in diff-in-diff regression{p_end}
{synopt :{cmdab:vce:(}{it:{help vce_option:vce_types}}{cmd:)}}Options for variance estimation. {hi:Robust}, {hi:cluster} {it:clustervar} or {hi:bootstrap}{p_end}
{synopt :{cmdab:starl:evels(}{it:numlist}{cmd:)}}Significance levels used for significance stars, default values are .1, .05 and .01{p_end}
{synopt :{cmdab:err:ortype(}{it:string}{cmd:)}}Type of errors to display, default is standard errors.{p_end}

{pstd}{it:Output options:}{p_end}
{synopt :{cmdab:rowl:abtype(}{it:string}{cmd:)}}Indicate what to use as row titles, default is variable name.{p_end}
{synopt :{cmdab:rowlabtext(}{it:label_string}{cmd:)}}Manually enter the row titles using label strings (see below).{p_end}
{synopt :{cmdab:nonote}}Disable that the automatically generated note is displayed below the table.{p_end}
{synopt :{cmdab:addn:otes(}{it:string}{cmd:)}}Manually add a note to be displayed below the regression result table.{p_end}
{synopt :{cmdab:onerow}}Display the number of observations on one row at the last row of the table.{p_end}
{synopt :{cmdab:format(}{it:{help format:%fmt}}{cmd:)}}Set the rounding format of the calculated statistics in the table.{p_end}
{synopt :{cmdab:replace}}Replace the file on disk if it already exist. Has no effect if no option with file path is used.{p_end}

{pstd}{it:LaTeX options:}{p_end}
{synopt :{cmdab:savet:ex(}{it:filepath}{cmd:)}}Generate a LaTeX table of the result and save to the location of the file path.{p_end}
{synopt :{cmdab:texdoc:ument}}Creates a stand-alone TeX document.{p_end}
{synopt :{cmdab:texc:aption(}{it:string}{cmd:)}}Specify table's caption on TeX file.{p_end}
{synopt :{cmdab:texl:abel(}{it:string}{cmd:)}}Specify table's label, used for meta-reference across TeX file.{p_end}
{synopt :{cmdab:texn:otewidth(}{it:numlist}{cmd:)}}Manually enter the width of the note on the TeX file.{p_end}
{synopt :{cmd:texvspace(}{it:string}{cmd:)}}Manually set size of the line space between two rows on TeX output.{p_end}
{synopt :{cmdab:nonumbers}}Ommit column numbers from table header in LaTeX output.{p_end}
{synoptline}

{marker desc}
{title:Description}

{pstd}{cmdab:ieddtab} is a command that makes it easy to run and display results of differences-in-differences (diff-in-diff) regressions. The table that presents the results from the diff-in-diff regression also presents the mean when the variable in {inp:time()} is 0 (i.e. baseline) for the two groups defined by the variable {inp:treatment()} is 0 and 1 (i.e. control and treatment), and the table also presents the coefficient of the first difference regression in control and treatment.{p_end}

{pstd}The sample for each row in the table is defined by the sample included in the second difference regression shown below, where {it:outcome_var} is a variable the varlist (one per row) for {inp:ieddtab}, {inp:`interaction'} is the interaction of the dummy listed in {inp:time()} and the dummy listed in {inp:treatment()}, and where {inp:`covariates'} is the list of covariates included in {inp:covariates()} if any. This means that any observation that has any missing value in either of the two dummies or in any of the covariates will be omitted from all statistics presented in the table. The coefficient presented in the table for the diff-in-diff regression is the interaction of the time and treatment variable.{p_end}

{pstd}{inp:tempvar} {it:interaction}{p_end}
{pstd}{inp:generate `interaction' = `time' * `treatment'}{p_end}
{pstd}{inp:regress} {it:outcome_var} {inp:`time' `treatment' `interaction' `covariates'}{p_end}

{pstd}The baseline means are then calculated using the following code where the first line is control and the second line is treatment, and the variable {inp:regsample} is dummy indicating if the observation was included in the second difference regression.{p_end}

{pstd}{inp:mean} {it:outcome_var} {inp:if `treatment' == 0 & `time' == 0 & regsample == 1}{p_end}
{pstd}{inp:mean} {it:outcome_var} {inp:if `treatment' == 1 & `time' == 0 & regsample == 1}{p_end}

{pstd}The first difference coefficients are then calculated using the following code where the first line is control and the second line is treatment. The coefficient displayed in the table is the coefficient of the variable `time' which is the variable listed in {inp:t()}.{p_end}

{pstd}{inp:regress} {it:outcome_var} {inp: `time' `covariates' if `treatment' == 0 & regsample == 1}{p_end}
{pstd}{inp:regress} {it:outcome_var} {inp: `time' `covariates' if `treatment' == 1 & regsample == 1}{p_end}

{marker optslong}
{title:Options}

{pstd}{it:{ul:{hi:Required options:}}}{p_end}
{phang}{cmdab:t(}{it:varname}{cmd:)} indicates which variable should be used as the time dummy to use in diff-in-diff regression. This must be a dummy variable, i.e. only have 0, 1 or missing as values, where 0 is baseline and 1 is follow-up.{p_end}

{phang}{cmdab:treatment(}{it:varname}{cmd:)} indicates which variable should be used as the treatment dummy to use in diff-in-diff regression. This must be a dummy variable, i.e. only have 0, 1 or missing as values.{p_end}

{pstd}{it:{ul:{hi:Statistics options:}}}{p_end}
{phang}{cmdab:covar:iates(}{it:varlist}{cmd:)} lists the variables that should be included as covariates (independent variables not reported in the table) in the two first difference regressions and the second diffrence regression. Unless the option {cmdab:nonotes} is used a list of covariate variables is included below the table.{p_end}

{phang}{cmdab:vce:(}{it:{help vce_option:vce_types}{cmd:)}} sets the type of variance estimator to be used in all regressions for this
command. See {help vce_option:vce_types} for more details. The only vce types allowed in this command are {hi:robust}, {hi:cluster} {it:clustervar} or {hi:bootstrap}.
Option {hi:robust} only applied to first and second difference estimators, not to baseline means.{p_end}

{phang}{cmdab:starl:evels(}{it:numlist}{cmd:)} sets the significance levels used for significance stars. Exactly three values must be listed if this option is used, all three values must be descending order, and must be between 0 and 1. The default values are .1, .05 and .01{p_end}

{phang}{cmdab:err:ortype(}{it:string}{cmd:)} sets the type of error to display. Allowed values for this iption is {inp:se} for standard errors, {inp:sd} for standard deviation and {inp:errhide} for not displaying any errors in the table. The default is to display standard errors.{p_end}

{pstd}{it:{ul:{hi:Output options:}}}{p_end}
{phang}{cmdab:rowl:abtype(}{it:string}{cmd:)} indicates what to use as row titles. The allowed values are {inp:varname} using the variable name as row titles, {inp:varlab} using the variable labels as row titles (varname will still be used if the variable does not have a variable label). The default is to use the variable name.{p_end}

{phang}{cmdab:rowlabtext(}{it:label_string}{cmd:)} manually specifies the row titles using label strings. A label string is a list of variable names followed by the row title for that variable separated by "@@". For example {it:varA Row title variable A @@ varB Row title variable B}, where {it:varA} and {it:varB} are outcome variables used in this command. For variable not listed in {cmdab:rowlabtext()} row titles will be determined by the input value or default value in {cmdab:rowl:abtype()}.{p_end}

{phang}{cmdab:nonotes} disable that the command automatically generates and displays a note below the table describing the output in the table. The note includes description on how number of calculations are calculated, the significance levels used for stars and which covariates were uses if any were used.{p_end}

{phang}{cmdab:addn:otes(}{it:string}{cmd:)} is used to manually add a note to be displayed below the regression result table. This note is put before the automatically generated note, unless option {cmdab:nonotes} is specified, in which case only the manually added note is displayed.{p_end}

{phang}{cmdab:onerow} indicates that the number of observations should be displayed on one row at the last row of the table instead on each row. This requires that the number of observations are the same across all rows for each column.{p_end}

{phang}{cmdab:format(}{it:{help format:%fmt}}{cmd:)} sets the number formatting/rounding rule for all calculated statistics in the table, that is all numbers in the table apart from the number of observations. Only valid {help format:Stata number formats} are allowed. The default is {it:%9.2f}.{p_end}

{phang}{cmdab:replace} if an option is used that output a file and a file with that name already exists at that location, then Stata will throw an error unless this option is used. If this option is used then Stata overwrites the file on disk with the new output. This option has no effect if no option with file path is used.{p_end}

{pstd}{it:{ul:{hi:LaTeX options:}}}{p_end}
{phang}{cmdab:savet:ex(}{it:filepath}{cmd:)} saves the table in TeX format to the location of the file path.{p_end}

{phang}{cmdab:texdoc:ument} creates a stand-alone TeX document that can be readily compiled, without the need to import it to a different file.
 As default, {cmd:savetex()} creates a fragmented TeX file consisting only of a tabular environment.

{phang}{cmdab:texc:aption(}{it:string}{cmd:)} writes table's caption in TeX file. Can only be used with option texdocument. {p_end}

{phang}{cmdab:texl:abel(}{it:string}{cmd:)} specifies table's label, used for meta-reference across TeX file. Can only be used with option texdocument.{p_end}

{phang}{cmdab:texn:otewidth(}{it:numlist}{cmd:)} manually adjusts the width of the note to fit the size of the table.
The note width is a multiple of text width. If not specified, default is one, which makes the table width equal to text width.{p_end}

{phang}{cmd:texvspace(}{it:string}{cmd:)} sets the size of the line space between two variable rows. {it:string} must consist of a numeric value
and one of the following units: "cm", "mm", "pt", "in", "ex" or "em". Note that the resulting line space displayed will be equal to the
specified value minus the height of one line of text. Default is "3ex". For more information on units,
{browse "https://en.wikibooks.org/wiki/LaTeX/Lengths":check LaTeX lengths manual}. {p_end}

{phang}{cmdab:nonumbers} ommits column numbers from table header in LaTeX output. Default is to display column numbers.{p_end}

{marker optslong}
{title:Examples}

{pstd}All the examples below can be run on the Stata's built in census data set, by first running this code:{p_end}

{pstd}*Open the built in data set{p_end}
{pstd}{inp:sysuse census}{p_end}

{pstd}*Calculate rates from absolute numbers{p_end}
{pstd}{inp:replace death = 100 * death / pop}{p_end}
{pstd}{inp:replace marriage = 100 * marriage / pop}{p_end}
{pstd}{inp:replace divorce = 100 * divorce / pop}{p_end}

{pstd}*Randomly assign time and treatment dummies{p_end}
{pstd}{inp:gen t	= (runiform()<.5)}{p_end}
{pstd}{inp:gen treatment = (runiform()<.5)}{p_end}

{pstd} {hi:Example 1.}

{pstd} {inp:ieddtab} {it:death marriage divorce} , {inp:t(}{it:time}{inp:)} {inp:treatment(}{it:treatment}{inp:)}

{pstd}This is the most basic way to run this command with three variables. This will output a table with the baseline means for treatment = 0 and treatment = 1, the first difference regression coefficient for treatment = 0 and treatment = 1 as well as the 2nd difference regression coefficient for treatment = 0 and treatment = 1.

{pstd} {hi:Example 2.}

{pstd} {inp:ieddtab} {it:death marriage divorce} ,  {inp:t(}{it:time}{inp:)} {inp:treatment(}{it:treatment}{inp:)}  {inp:rowlabtext(}{it:"death Death Rate @@ divorce Divorce Rate"}{inp:)} {inp:rowlabtype(}{it:"varlab"}{inp:)}

{pstd}The table generated by example 2 will have the same statistics as in example 1 but the row title for the variables death and divorce are entered manually and the row title for marriage will be its variable label instead of its variable name.

{pstd} {hi:Example 3.}

{pstd} {inp:ieddtab} {it:death marriage divorce} ,  {inp:t(}{it:time}{inp:)} {inp:treatment(}{it:treatment}{inp:)}  {inp:rowlabtype(}{it:"varlab"}{inp:)} {inp:savetex(}{it:"DID table.tex"}{inp:)} {inp:replace}

{pstd}The table will be saved in the current directory under the name "DID table.tex". It will will have the same statistics as in examples 1 and 2, and the row titles will be its variable labels.

{title:Acknowledgements}

{phang}This command was initally suggested by Esteban J. Quinones, University of Wisconsin-Madison{p_end}

{phang}We would like to acknowledge the help in testing and proofreading we received in relation to this command and help file from (in alphabetic order):{p_end}
{pmore}Benjamin Daniels{break}Jonas Guthoff{break}Nausheen Khan{break}Varnitha Kurli{break}Saori Iwamoto{break}Meyhar Mohammed{break}Michael Orevba{break}Matteo Ruzzante{break}Sakina Shibuya{break}Leonardo Viotti{break}

{title:Author}

{phang}All commands in ietoolkit is developed by DIME Analytics at DECIE, The World Bank's unit for Development Impact Evaluations.{p_end}

{phang}Main author: Kristoffer Bjarkefur, Luiza Cardoso De Andrade, DIME Analytics, The World Bank Group{p_end}

{phang}Please send bug-reports, suggestions and requests for clarifications
		 writing "ietoolkit ieddtab" in the subject line to:{break}
		 dimeanalytics@worldbank.org{p_end}

{phang}You can also see the code, make comments to the code, see the version
		 history of the code, and submit additions or edits to the code through
		 the GitHub repository of ietoolkit:{break}
{browse "https://github.com/worldbank/ietoolkit"}{p_end}

{smcl}
{* 19 Oct 2018}{...}
{hline}
help for {hi:ieddtab}
{hline}

{title:Title}

{phang2}{cmdab:ieddtab} {hline 2} This command runs a Diff-in-Diff regression and displays the baseline values, the two 1st differences and the 2nd difference.

{phang2}For a more descriptive discussion on the intended usage and work flow of this
command please see the {browse "https://dimewiki.worldbank.org/wiki/ieddtab":DIME Wiki}.

{title:Syntax}

{phang2} {cmdab:ieddtab} {it:varlist} [{help if}] [{help in}] [{help weight}],
	{cmdab:t:ime(}{it:varname}{cmd:)} {cmdab:treat:ment(}{it:varname}{cmd:)}
		{break}[
		{cmdab:covar:iates(}{it:varlist}{cmd:)} {cmdab:starl:evels(}{it:numlist}{cmd:)}
		{cmdab:err:ortype(}{it:string}{cmd:)} {cmdab:rowl:abtype(}{it:string}{cmd:)}
		{cmdab:rowlabtext(}{it:label_string}{cmd:)} {cmdab:format(}{it:{help format:%fmt}}{cmd:)}
		{cmdab:replace} {cmdab:savet:ex(}{it:filepath}{cmd:)} {cmdab:onerow}
		{cmdab:nonotes} {cmdab:addn:otes(}{it:string}{cmd:)}  {cmdab:texdoc:ument}
		{cmdab:texc:aption(}{it:string}{cmd:)} {cmdab:texl:abel(}{it:string}{cmd:)}
		{cmdab:texn:otewidth(}{it:numlist}{cmd:)} {cmdab:texvspace(}{it:string}{cmd:)}
	]

{pmore}Where {it:varlist} is a list of numeric continuous outcome variables (also called dependent variables or left hand side variables) to be used in the difference-in-difference regression(s) this command runs and presents the results from.{p_end}

{marker opts}{...}
{synoptset 24}{...}
{synopthdr:options}
{synoptline}
{pstd}{it:Required options:}{p_end}
{synopt :{cmdab:t:ime(}{it:varname}{cmd:)}}Time dummy to use in diff-in-diff regression{p_end}
{synopt :{cmdab:treat:ment(}{it:varname}{cmd:)}}Treatment dummy to use in diff-in-diff regression{p_end}

{pstd}{it:Statistics options:}{p_end}
{synopt :{cmdab:covar:iates(}{it:varlist}{cmd:)}}Covariates to use in diff-in-diff regression{p_end}
{synopt :{cmdab:vce:(}{it:{help vce_option:vce_types}}{cmd:)}}Options for variance estimation. {hi:Robust}, {hi:cluster} {it:clustervar} or {hi:bootstrap}{p_end}
{synopt :{cmdab:starl:evels(}{it:numlist}{cmd:)}}Significance levels used for significance stars, default values are .1, .05 and .01{p_end}
{synopt :{cmdab:err:ortype(}{it:string}{cmd:)}}Type of errors to display, default is standard errors.{p_end}

{pstd}{it:Output options:}{p_end}
{synopt :{cmdab:rowl:abtype(}{it:string}{cmd:)}}Indicate what to use as row titles, default is variable name.{p_end}
{synopt :{cmdab:rowlabtext(}{it:label_string}{cmd:)}}Manually enter the row titles using label strings (see below).{p_end}
{synopt :{cmdab:nonote}}Disable that the automatically generated note is displayed below the table.{p_end}
{synopt :{cmdab:addn:otes(}{it:string}{cmd:)}}Manually add a note to be displayed below the regression result table.{p_end}
{synopt :{cmdab:onerow}}Display the number of observations on one row at the last row of the table.{p_end}
{synopt :{cmdab:format(}{it:{help format:%fmt}}{cmd:)}}Set the rounding format of the calculated statistics in the table.{p_end}
{synopt :{cmdab:replace}}Replace the file on disk if it already exist. Has no effect if no option with file path is used.{p_end}

{pstd}{it:LaTeX options:}{p_end}
{synopt :{cmdab:savet:ex(}{it:filepath}{cmd:)}}Generate a LaTeX table of the result and save to the location of the file path.{p_end}
{synopt :{cmdab:texdoc:ument}}Creates a stand-alone TeX document.{p_end}
{synopt :{cmdab:texc:aption(}{it:string}{cmd:)}}Specify table's caption on TeX file.{p_end}
{synopt :{cmdab:texl:abel(}{it:string}{cmd:)}}Specify table's label, used for meta-reference across TeX file.{p_end}
{synopt :{cmdab:texn:otewidth(}{it:numlist}{cmd:)}}Manually enter the width of the note on the TeX file.{p_end}
{synopt :{cmd:texvspace(}{it:string}{cmd:)}}Manually set size of the line space between two rows on TeX output.{p_end}
{synoptline}

{marker desc}
{title:Description}

{pstd}{cmdab:ieddtab} is a command that makes it easy to run and display results of differences-in-differences (diff-in-diff) regressions. The table that presents the results from the diff-in-diff regression also presents the mean when the variable in {inp:time()} is 0 (i.e. baseline) for the two groups defined by the variable {inp:treatment()} is 0 and 1 (i.e. control and treatment), and the table also presents the coefficient of the first difference regression in control and treatment.{p_end}

{pstd}The sample for each row in the table is defined by the sample included in the second difference regression shown below, where {it:outcome_var} is a variable the varlist (one per row) for {inp:ieddtab}, {inp:`interaction'} is the interaction of the dummy listed in {inp:time()} and the dummy listed in {inp:treatment()}, and where {inp:`covariates'} is the list of covariates included in {inp:covariates()} if any. This means that any observation that has any missing value in either of the two dummies or in any of the covariates will be omitted from all statistics presented in the table. The coefficient presented in the table for the diff-in-diff regression is the interaction of the time and treatment variable.{p_end}

{pstd}{inp:tempvar} {it:interaction}{p_end}
{pstd}{inp:generate `interaction' = `time' * `treatment'}{p_end}
{pstd}{inp:regress} {it:outcome_var} {inp:`time' `treatment' `interaction' `covariates'}{p_end}

{pstd}The baseline means are then calculated using the following code where the first line is control and the second line is treatment, and the variable {inp:regsample} is dummy indicating if the observation was included in the second difference regression.{p_end}

{pstd}{inp:mean} {it:outcome_var} {inp:if `treatment' == 0 & `time' == 0 & regsample == 1}{p_end}
{pstd}{inp:mean} {it:outcome_var} {inp:if `treatment' == 1 & `time' == 0 & regsample == 1}{p_end}

{pstd}The first difference coefficients are then calculated using the following code where the first line is control and the second line is treatment. The coefficient displayed in the table is the coefficient of the variable `time' which is the variable listed in {inp:t()}.{p_end}

{pstd}{inp:regress} {it:outcome_var} {inp: `time' `covariates' if `treatment' == 0 & regsample == 1}{p_end}
{pstd}{inp:regress} {it:outcome_var} {inp: `time' `covariates' if `treatment' == 1 & regsample == 1}{p_end}

{marker optslong}
{title:Options}

{pstd}{it:{ul:{hi:Required options:}}}{p_end}
{phang}{cmdab:t(}{it:varname}{cmd:)} indicates which variable should be used as the time dummy to use in diff-in-diff regression. This must be a dummy variable, i.e. only have 0, 1 or missing as values, where 0 is baseline and 1 is follow-up.{p_end}

{phang}{cmdab:treatment(}{it:varname}{cmd:)} indicates which variable should be used as the treatment dummy to use in diff-in-diff regression. This must be a dummy variable, i.e. only have 0, 1 or missing as values.{p_end}

{pstd}{it:{ul:{hi:Statistics options:}}}{p_end}
{phang}{cmdab:covar:iates(}{it:varlist}{cmd:)} lists the variables that should be included as covariates (independent variables not reported in the table) in the two first difference regressions and the second diffrence regression. Unless the option {cmdab:nonotes} is used a list of covariate variables is included below the table.{p_end}

{phang}{cmdab:vce:(}{it:{help vce_option:vce_types}{cmd:)}} sets the type of variance estimator to be used in all regressions for this
command. See {help vce_option:vce_types} for more details. The only vce types allowed in this command are {hi:robust}, {hi:cluster} {it:clustervar} or {hi:bootstrap}.
Option {hi:robust} only applied to first and second difference estimators, not to baseline means.{p_end}

{phang}{cmdab:starl:evels(}{it:numlist}{cmd:)} sets the significance levels used for significance stars. Exactly three values must be listed if this option is used, all three values must be descending order, and must be between 0 and 1. The default values are .1, .05 and .01{p_end}

{phang}{cmdab:err:ortype(}{it:string}{cmd:)} sets the type of error to display. Allowed values for this iption is {inp:se} for standard errors, {inp:sd} for standard deviation and {inp:errhide} for not displaying any errors in the table. The default is to display standard errors.{p_end}

{pstd}{it:{ul:{hi:Output options:}}}{p_end}
{phang}{cmdab:rowl:abtype(}{it:string}{cmd:)} indicates what to use as row titles. The allowed values are {inp:varname} using the variable name as row titles, {inp:varlab} using the variable labels as row titles (varname will still be used if the variable does not have a variable label). The default is to use the variable name.{p_end}

{phang}{cmdab:rowlabtext(}{it:label_string}{cmd:)} manually specifies the row titles using label strings. A label string is a list of variable names followed by the row title for that variable separated by "@@". For example {it:varA Row title variable A @@ varB Row title variable B}, where {it:varA} and {it:varB} are outcome variables used in this command. For variable not listed in {cmdab:rowlabtext()} row titles will be determined by the input value or default value in {cmdab:rowl:abtype()}.{p_end}

{phang}{cmdab:nonotes} disable that the command automatically generates and displays a note below the table describing the output in the table. The note includes description on how number of calculations are calculated, the significance levels used for stars and which covariates were uses if any were used.{p_end}

{phang}{cmdab:addn:otes(}{it:string}{cmd:)} is used to manually add a note to be displayed below the regression result table. This note is put before the automatically generated note, unless option {cmdab:nonotes} is specified, in which case only the manually added note is displayed.{p_end}

{phang}{cmdab:onerow} indicated that the number of observations should be displayed on one row at the last row of the table instead on each row. This requires that the number of observations are the same across all rows for each column.{p_end}

{phang}{cmdab:format(}{it:{help format:%fmt}}{cmd:)} sets the number formatting/rounding rule for all calculated statistics in the table, that is all numbers in the table apart from the number of observations. Only valid {help format:Stata number formats} are allowed. The default is {it:%9.2f}.{p_end}

{phang}{cmdab:replace} if an option is used that output a file and a file with that name already exists at that location, then Stata will throw an error unless this option is used. If this option is used then Stata overwrites the file on disk with the new output. This option has no effect if no option with file path is used.{p_end}

{pstd}{it:{ul:{hi:LaTeX options:}}}{p_end}
{phang}{cmdab:savet:ex(}{it:filepath}{cmd:)} saves the table in TeX format to the location of the file path.{p_end}

{phang}{cmdab:texdoc:ument} creates a stand-alone TeX document that can be readily compiled, without the need to import it to a different file.
 As default, {cmd:savetex()} creates a fragmented TeX file consisting only of a tabular environment.

{phang}{cmdab:texc:aption(}{it:string}{cmd:)} writes table's caption in TeX file. Can only be used with option texdocument. {p_end}

{phang}{cmdab:texl:abel(}{it:string}{cmd:)} specifies table's label, used for meta-reference across TeX file. Can only be used with option texdocument.{p_end}

{phang}{cmdab:texn:otewidth(}{it:numlist}{cmd:)} manually adjusts the width of the note to fit the size of the table.
The note width is a multiple of text width. If not specified, default is one, which makes the table width equal to text width.{p_end}

{phang}{cmd:texvspace(}{it:string}{cmd:)} sets the size of the line space between two variable rows. {it:string} must consist of a numeric value
and one of the following units: "cm", "mm", "pt", "in", "ex" or "em". Note that the resulting line space displayed will be equal to the
specified value minus the height of one line of text. Default is "3ex". For more information on units,
{browse "https://en.wikibooks.org/wiki/LaTeX/Lengths":check LaTeX lengths manual}. {p_end}

{marker optslong}
{title:Examples}

{pstd}All the examples below can be run on the Stata's built in census data set, by first running this code:{p_end}

{pstd}*Open the built in data set{p_end}
{pstd}{inp:sysuse census}{p_end}

{pstd}*Calculate rates from absolute numbers{p_end}
{pstd}{inp:replace death = 100 * death / pop}{p_end}
{pstd}{inp:replace marriage = 100 * marriage / pop}{p_end}
{pstd}{inp:replace divorce = 100 * divorce / pop}{p_end}

{pstd}*Randomly assign time and treatment dummies{p_end}
{pstd}{inp:gen t	= (runiform()<.5)}{p_end}
{pstd}{inp:gen treatment = (runiform()<.5)}{p_end}

{pstd} {hi:Example 1.}

{pstd} {inp:ieddtab} {it:death marriage divorce} , {inp:t(}{it:time}{inp:)} {inp:treatment(}{it:treatment}{inp:)}

{pstd}This is the most basic way to run this command with three variables. This will output a table with the baseline means for treatment = 0 and treatment = 1, the first difference regression coefficient for treatment = 0 and treatment = 1 as well as the 2nd difference regression coefficient for treatment = 0 and treatment = 1.

{pstd} {hi:Example 2.}

{pstd} {inp:ieddtab} {it:death marriage divorce} ,  {inp:t(}{it:time}{inp:)} {inp:treatment(}{it:treatment}{inp:)}  {inp:rowlabtext(}{it:"death Death Rate @@ divorce Divorce Rate"}{inp:)} {inp:rowlabtype(}{it:"varlab"}{inp:)}

{pstd}The table generated by example 2 will have the same statistics as in example 1 but the row title for the variables death and divorce are entered manually and the row title for marriage will be its variable label instead of its variable name.

{pstd} {hi:Example 3.}

{pstd} {inp:ieddtab} {it:death marriage divorce} ,  {inp:t(}{it:time}{inp:)} {inp:treatment(}{it:treatment}{inp:)}  {inp:rowlabtype(}{it:"varlab"}{inp:)} {inp:savetex(}{it:"DID table.tex"}{inp:)} {inp:replace}

{pstd}The table will be saved in the current directory under the name "DID table.tex". It will will have the same statistics as in examples 1 and 2, and the row titles will be its variable labels.

{title:Acknowledgements}

{phang}This command was initally suggested by Esteban J. Quinones, University of Wisconsin-Madison{p_end}

{phang}We would like to acknowledge the help in testing and proofreading we received in relation to this command and help file from (in alphabetic order):{p_end}
{pmore}Benjamin Daniels{break}Jonas Guthoff{break}Nausheen Khan{break}Varnitha Kurli{break}Saori Iwamoto{break}Meyhar Mohammed{break}Michael Orevba{break}Matteo Ruzzante{break}Sakina Shibuya{break}Leonardo Viotti{break}

{title:Author}

{phang}All commands in ietoolkit is developed by DIME Analytics at DECIE, The World Bank's unit for Development Impact Evaluations.{p_end}

{phang}Main author: Kristoffer Bjarkefur, Luiza Cardoso De Andrade, DIME Analytics, The World Bank Group{p_end}

{phang}Please send bug-reports, suggestions and requests for clarifications
		 writing "ietoolkit ieddtab" in the subject line to:{break}
		 dimeanalytics@worldbank.org{p_end}

{phang}You can also see the code, make comments to the code, see the version
		 history of the code, and submit additions or edits to the code through
		 the GitHub repository of ietoolkit:{break}
{browse "https://github.com/worldbank/ietoolkit"}{p_end}


iematch : issue #111 - update helpfile for replace

{smcl}
{* 14 Nov 2017}{...}
{hline}
help for {hi:iematch}
{hline}

{title:Title}

{phang2}{cmdab:iematch} {hline 2} Matching base observations towards target observations using on a single continous variable.

{title:Syntax}

{phang2}
{cmdab:iematch} {ifin}
, {cmdab:grp:dummy(}{it:varname}{cmd:)} {cmdab:match:var(}{it:varname}{cmd:)}
[{cmdab:id:var(}{it:varname}{cmd:)} {cmdab:m1} {cmdab:maxdiff(}{it:numlist}{cmd:)} {cmd:seedok}
{cmdab:matchid:name(}{it:string}{cmd:)} {cmdab:matchdi:ffname(}{it:string}{cmd:)}
{cmdab:matchre:sultname(}{it:string}{cmd:)} {cmdab:matchco:untname(}{it:string}{cmd:)}
{cmdab:replace}]

{marker opts}{...}
{synoptset 22}{...}
{synopthdr:options}
{synoptline}
{synopt :{cmdab:grp:dummy(}{it:varname}{cmd:)}}The group dummy variable where 1
	indicates base observations and 0 target observations{p_end}
{synopt :{cmdab:match:var(}{it:varname}{cmd:)}}The variable with a continous value
	to match on{p_end}
{synopt :{cmdab:id:var(}{it:varname}{cmd:)}}The uniquely and fully identifying ID
	varaible. Used to indicate which target observation a base observation is match
	with. If omitted an ID variable will be created. See below if you have multiple ID vars.{p_end}
{synopt :{cmdab:m1}}Allows many-to-one matches. The default is to allow only
	one-to-one matches. See the {help iematch##desc:description} section.{p_end}
{synopt :{cmdab:maxdiff(}{it:numlist}{cmd:)}}Set a maximum difference allowed in
	{cmdab:matchvar()}. If a base observation has no match within this difference
 then it will remain unmatched{p_end}
{synopt :{cmd:seedok}}Supresses the error maessage thrown when there are duplicates
	in {cmd:matchvar()}. When there are duplicates, the seed needs to be set in order
	to have a replicable match. The {help seed} should be set before this command.{p_end}
{synopt :{cmdab:matchre:sultname(}{it:string}{cmd:)}}Manually sets the name of
	the variable that indicates if an observation was matched, or provide a reason why
	it was not. The default is _matchResult{p_end}
{synopt :{cmdab:matchid:name(}{it:string}{cmd:)}}Manually sets the name of the
	variable that indicates which target observation each base observation is
	matched with. The default is _matchID{p_end}
{synopt :{cmdab:matchdi:ffname(}{it:string}{cmd:)}}Manually sets the name of the
	variable that indicates the differnece in {cmdab:matchvar()} in each match
	pair/group. The default is _matchDiff{p_end}
{synopt :{cmdab:matchco:untname(}{it:string}{cmd:)}}Manually sets the name of the
	variable that indicates how many observations a target obsersvation is matched
	with in a many-to-one matches. The default is _matchCount{p_end}
{synopt :{cmd:replace}}Replaces variables in memory if there are name conflicts
	when generating the output variables.{p_end}
{synoptline}

{marker desc}
{title:Description}

{pstd}{cmdab:iematch} matches base observations towards target observations in terms
	of nearest value in {cmd:matchvar()}. Base observations are observations with
	value 1 in {cmd:grpdummy()} and target observations are observations with value
	0. For example, in a typical p-score match, base observations are treatment and
	target is control, however, there are many other examples of matching where it could
	be different.

{pstd}{cmdab:iematch} bases its matching algorithm on the Stable Marriage algorithm.
	This algorithm was chosen because it always provides a solution and allows stable
	matching even if multiple observations have identical match
	values (see {cmd:seed()} option for more details). One disadvantage of this
	algorithm is that it takes into account local efficiency only, and not global efficiency. This
	means that it is possible that other matching algorithms might generate a more
	efficient match in terms of the sum of the difference of all matched pairs/groups.

{pstd}{hi:{ul:One-to-one matching algorithm}}{break}
	The algorithm used in a one-to-one match starts by evaluating which
	target observation each base observation is closest to and vice versa for each
	target observations. If a base and target observation pair mutually prefer
	each other, then these two observations are matched. The algorithm then repeats
	the initial two evaluation steps, and excludes observations after they are matched,
	until all base observations are either matched or excluded due to the option {cmdab:maxdiff()}.
	Matched observations ends up in pairs of exactly one base observation and one
	target observation.

{pstd}In a one-to-one match, there has to be at least as many target observations
	as there are base observations. A one-to-one match returns three variables. One
	variable indicates the result of the matching for each observation, such as,
	matched, not matched, no match within the max difference, etc. The other two variables
	hold information on the matched pair. One variable is the ID of the target observation
	in the matched pair, and the other variable is the difference in {cmd:matchvar()}
	between the two observations in the match pair. See the below in this section
	for more details on the variables generated.

{pstd}{hi:{ul:Many-to-one matching algorithm}}{break}
	The algorithm used for many-to-one matching is the same as in a one-to-one match. But instead
	of matching only when there is a mutual preference, all base observations are
	matched towards their preferred target observation in the first step, as long
	as the match is within the max-value if {cmdab:maxdff()} is used. Matched observations
	end up in groups in which there is exactly one target observation but where there are
	either one or several base observations.

{pstd}In a many-to-one match, there is no restriction in terms of the number of
	base observations in relation to target observations. The many-to-one matching
	yields four variables. Three of the variables are the same as in one-to-one
	matching, and only the variable listing the difference  The fourth variable indicates how many base observations that were matched
	towards each target observation. See the below in this section for more details on
	the variables generated.

{pstd}{hi:{ul:Variables generated}}{break}
	This section explains the variables that are generated by this command. All variables
	will be referred to by their default names, but those names can be manually set to somthing
	else (see the options for this command).

{pstd}{hi:_matchResult}{break}
	This variable indicates the result of the match for all observations. Observations
	that ended up in a match pair/group has the value 1. Target observations not matched have the
	value 0. Base observations without a valid match due to {cmdab:maxdff()} are
	assigned the value .d. Observations excluded from the match using {inp:if}/{inp:in} are
	assigned the value .i. Observations excluded from the match due to missing value in {cmd:grpdummy()} are
	assigned the value .g. Observations excluded from the match due to missing value in {cmd:matchvar()} are
	assigned the value .m. All values have descreptive value labels.

{pstd}{hi:_matchID}{break}
	This variable indicates the ID of the target observations in each match pair/group. For matched
	target observations, the value in _matchID will be equal to the value in the ID
	variable. Since the values in the ID varaible are unique and there is exactly one target
	observation in each matched pair/group, this variable functions as a unique pair/group ID.
	In addition to indicating which observations are included in the same pair/group, this
	varaible can be used to include a pair/group fixed effect in a regression.

{pstd}{hi:_matchDiff}{break}
	This variable indicates the difference in {cmd:matchvar()} between matched base observations
	and target observations. In a one-to-one match this value is the identical for
	both the base observation and the target observation in each matched pair.
	In a many-to-one match, this value is only indicated for base observations. It is
	missing for target observations as there are potentially multiple matches, and
	subsequently multiple differences.

{pstd}{hi:_matchCount}{break}
	In a many-to-one match, this variable indicates how many base observations were
	matched towards each matched target observation. This variable can be used as regression
	weights when controlling for the fact that some observations are matched towards multiple
	observations.

{marker optslong}
{title:Options}

{phang}{cmdab:grp:dummy(}{it:varname}{cmd:)} is the dummy variable that indicates if an observation
	is a base or target observation. This variable, must be numeric and is only allowed to have
	the values 1, 0 or missing. 1 indicates a base observation, 0 indicates a target observation,
	and observations with a missing value will be excluded from the matching.

{phang}{cmdab:match:var(}{it:varname}{cmd:)} is the variable used to compare observations when
	matching. This must be a numeric variable, and it is typically a continuous
	variable. Observations with a missing value will be excluded from the matching.

{phang}{cmdab:id:var(}{it:varname}{cmd:)} indicates the variable that uniquely
	and fully identifies the data set. The values in this variable is the values
	that will be used in the variable that indicates which target observation each
	base observations matched against. If this option is omitted, a variable called
	_ID will be generated. The observation in the first row is given the value 1,
	the second row value 2 and so fourth.

{pmore}This command assumes only one ID variable as that is the best practice this command
	follows (see next paragraph for the exception of panel data sets). Here follows two
	suggested solutions if a data set this command will be used on has more than one ID
	variable. {bf:1.} Do not use the {cmd:idvar()} option and after the mathcing copy the mutliple
	ID variables yourself. {bf:2.} Combine your ID variables into one ID variable. Here are two
	examples on how that can be done (the examples below work just as well when combining more
	than two ID variables to one.):

{pmore2}{inp:egen }{it:new_ID_var }{inp:= group(}{it:old_ID_var1 old_ID_var2}{inp:)}

{pmore2}{inp:gen}{space 2}{it:new_ID_var }{inp:= }{it:old_ID_var1 }{inp:+ "_" + }{it:old_ID_var2}{space 4}//Works only with string vars

{pmore}Panel data sets are one of the few cases where multiple ID variables is good practice. However,
	in the case of matching it is unlikely that it is correct to include multiple time rounds for
	the same observation. That would lead to some base observations being matched to
	one target observation in the first round, and one another in the second. In impact
	evaluations, matchings are almost exclusively done only on the baseline data.

{phang}{cmdab:m1} sets the match to a many-to-one match (see {help iematch##desc:description}).
	This allows multiple base observations to be matched towards a single target observation.
	The default is the one-to-one match where a maximum one base observation is matched towards
	each target observation. This option allows the number of base observations
	to be larger then the number of target observations.

{phang}{cmdab:maxdiff(}{it:numlist}{cmd:)} sets a maximum allowed difference between
	a base observation and a target observation for a match to be valid. Any base
	observation without a valid match within this difference will end up unmatched.

{phang}{cmd:seedok} supresses the error message throwned when there are duplicates among
	the base observations or the target observations in {cmd:matchvar()}. When there
	are duplicates a random variable is used to distinguish which variable to match.
	Setting the seed makes this randomization replicable and thereby making the matching
	also replicable. The {help seed} should be set before this command by the user. When the
	seed is set, or if replicable matching is not important, then the option {cmd:seedok} can
	be used to supress the error message. Duplicate pairs where one observation is a base
	observation and the other is a target observations are allowed.

{phang}{cmdab:matchre:sultname(}{it:string}{cmd:)} manually sets the
	name of the variable that reports the matching result for each observation.
	If omitted, the default name is {inp:_matchResult}. The names {inp:_ID},
	{inp:_matchID}, {inp:_matchDiff} and {inp:_matchCount} are not allowed.

{phang}{cmdab:matchid:name(}{it:string}{cmd:)} manually sets the
	name of the variable that list the ID of the target observations in each match pair/group.
	If omitted, the default name is {inp:_matchID}. The names {inp:_ID}, {inp:_matchDiff}, {inp:_matchResult}
	and {inp:_matchCount} are not allowed.

{phang}{cmdab:matchdi:ffname(}{it:string}{cmd:)} manually sets the name of the variable
	that indicates the difference between the matched base observations
	and target observations. If omitted, the default name is {inp:_matchDiff}. The
	names {inp:_ID}, {inp:_matchID}, {inp:_matchResult} and {inp:_matchCount} are
	not allowed.

{phang}{cmdab:matchco:untname(}{it:string}{cmd:)} manually sets the
	name of the variable that indicates the number of base observations that has
	been matched towards each matched matched target observation. This option may
	only be used in combination with option {cmd:m1}. If omitted, the default
	name is {inp:_matchCount}. The names {inp:_ID}, {inp:_matchID}, {inp:_matchDiff}
	and {inp:_matchResult} are not allowed.

{phang}{cmdab:replace} allows {cmd:iematch} to replace variables in memory when
	encountering name conflicts while creating the variables with the results of the matching.

{title:Examples}

{pstd} {hi:Example 1.}

{pmore}{inp:iematch , grpdummy({it:tmt}) matchvar({it:p_hat})}

{pmore}In the example above, the observations with value 1 in {it:tmt} will be matched
	towards the nearest, in terms of {it:p_hat}, observations with value 0 in {it:tmt}.

{pstd} {hi:Example 2.}

{pmore}{inp:iematch if {it:baseline} == 1  , grpdummy({it:tmt}) matchvar({it:p_hat}) maxdiff(.001)}

{pmore}In the example above, the observations with value 1 in {it:tmt} will be matched
	towards the nearest, in terms of {it:p_hat}, observations with value 0 in {it:tmt} as
	long as the difference in {it:p_hat} is less than .001. Only observations that has the
	value 1 in variable {it:baseline} will be included in the match.

{title:Acknowledgements}

{phang}I would like to acknowledge the help in testing and proofreading I received in relation to this command and help file from (in alphabetic order):{p_end}
{pmore}Luiza Cardoso De Andrade{break}Seungmin Lee{break}Mrijan Rimal{break}

{title:Author}

{phang}Kristoffer Bjarkefur, The World Bank, DECIE

{phang}Please send bug-reports, suggestions and requests for clarifications
		 writing "ietools iematch" in the subject line to:{break}
		 kbjarkefur@worldbank.org

{phang}You can also see the code, make comments to the code, see the version
		 history of the code, and submit additions or edits to the code through
		 the github repository of ietoolkit:{break}
		 {browse "https://github.com/worldbank/ietoolkit"}

{smcl}
{* 14 Nov 2017}{...}
{hline}
help for {hi:iematch}
{hline}

{title:Title}

{phang2}{cmdab:iematch} {hline 2} Matching base observations towards target observations using on a single continous variable.

{title:Syntax}

{phang2}
{cmdab:iematch} {ifin}
, {cmdab:grp:dummy(}{it:varname}{cmd:)} {cmdab:match:var(}{it:varname}{cmd:)}
[{cmdab:id:var(}{it:varname}{cmd:)} {cmdab:m1} {cmdab:maxdiff(}{it:numlist}{cmd:)} {cmd:seedok}
{cmdab:matchid:name(}{it:string}{cmd:)} {cmdab:matchdi:ffname(}{it:string}{cmd:)}
{cmdab:matchre:sultname(}{it:string}{cmd:)} {cmdab:matchco:untname(}{it:string}{cmd:)}
]

{marker opts}{...}
{synoptset 22}{...}
{synopthdr:options}
{synoptline}
{synopt :{cmdab:grp:dummy(}{it:varname}{cmd:)}}The group dummy variable where 1
	indicates base observations and 0 target observations{p_end}
{synopt :{cmdab:match:var(}{it:varname}{cmd:)}}The variable with a continous value
	to match on{p_end}
{synopt :{cmdab:id:var(}{it:varname}{cmd:)}}The uniquely and fully identifying ID
	varaible. Used to indicate which target observation a base observation is match
	with. If omitted an ID variable will be created. See below if you have multiple ID vars.{p_end}
{synopt :{cmdab:m1}}Allows many-to-one matches. The default is to allow only
	one-to-one matches. See the {help iematch##desc:description} section.{p_end}
{synopt :{cmdab:maxdiff(}{it:numlist}{cmd:)}}Set a maximum difference allowed in
	{cmdab:matchvar()}. If a base observation has no match within this difference
 then it will remain unmatched{p_end}
{synopt :{cmd:seedok}}Supresses the error maessage thrown when there are duplicates
	in {cmd:matchvar()}. When there are duplicates, the seed needs to be set in order
	to have a replicable match. The {help seed} should be set before this command.{p_end}
{synopt :{cmdab:matchre:sultname(}{it:string}{cmd:)}}Manually sets the name of
	the variable that indicates if an observation was matched, or provide a reason why
	it was not. The default is _matchResult{p_end}
{synopt :{cmdab:matchid:name(}{it:string}{cmd:)}}Manually sets the name of the
	variable that indicates which target observation each base observation is
	matched with. The default is _matchID{p_end}
{synopt :{cmdab:matchdi:ffname(}{it:string}{cmd:)}}Manually sets the name of the
	variable that indicates the differnece in {cmdab:matchvar()} in each match
	pair/group. The default is _matchDiff{p_end}
{synopt :{cmdab:matchco:untname(}{it:string}{cmd:)}}Manually sets the name of the
	variable that indicates how many observations a target obsersvation is matched
	with in a many-to-one matches. The default is _matchCount{p_end}
{synoptline}

{marker desc}
{title:Description}

{pstd}{cmdab:iematch} matches base observations towards target observations in terms
	of nearest value in {cmd:matchvar()}. Base observations are observations with
	value 1 in {cmd:grpdummy()} and target observations are observations with value
	0. For example, in a typical p-score match, base observations are treatment and
	target is control, however, there are many other examples of matching where it could
	be different.

{pstd}{cmdab:iematch} bases its matching algorithm on the Stable Marriage algorithm.
	This algorithm was chosen because it always provides a solution and allows stable
	matching even if multiple observations have identical match
	values (see {cmd:seed()} option for more details). One disadvantage of this
	algorithm is that it takes into account local efficiency only, and not global efficiency. This
	means that it is possible that other matching algorithms might generate a more
	efficient match in terms of the sum of the difference of all matched pairs/groups.

{pstd}{hi:{ul:One-to-one matching algorithm}}{break}
	The algorithm used in a one-to-one match starts by evaluating which
	target observation each base observation is closest to and vice versa for each
	target observations. If a base and target observation pair mutually prefer
	each other, then these two observations are matched. The algorithm then repeats
	the initial two evaluation steps, and excludes observations after they are matched,
	until all base observations are either matched or excluded due to the option {cmdab:maxdiff()}.
	Matched observations ends up in pairs of exactly one base observation and one
	target observation.

{pstd}In a one-to-one match, there has to be at least as many target observations
	as there are base observations. A one-to-one match returns three variables. One
	variable indicates the result of the matching for each observation, such as,
	matched, not matched, no match within the max difference, etc. The other two variables
	hold information on the matched pair. One variable is the ID of the target observation
	in the matched pair, and the other variable is the difference in {cmd:matchvar()}
	between the two observations in the match pair. See the below in this section
	for more details on the variables generated.

{pstd}{hi:{ul:Many-to-one matching algorithm}}{break}
	The algorithm used for many-to-one matching is the same as in a one-to-one match. But instead
	of matching only when there is a mutual preference, all base observations are
	matched towards their preferred target observation in the first step, as long
	as the match is within the max-value if {cmdab:maxdff()} is used. Matched observations
	end up in groups in which there is exactly one target observation but where there are
	either one or several base observations.

{pstd}In a many-to-one match, there is no restriction in terms of the number of
	base observations in relation to target observations. The many-to-one matching
	yields four variables. Three of the variables are the same as in one-to-one
	matching, and only the variable listing the difference  The fourth variable indicates how many base observations that were matched
	towards each target observation. See the below in this section for more details on
	the variables generated.

{pstd}{hi:{ul:Variables generated}}{break}
	This section explains the variables that are generated by this command. All variables
	will be referred to by their default names, but those names can be manually set to somthing
	else (see the options for this command).

{pstd}{hi:_matchResult}{break}
	This variable indicates the result of the match for all observations. Observations
	that ended up in a match pair/group has the value 1. Target observations not matched have the
	value 0. Base observations without a valid match due to {cmdab:maxdff()} are
	assigned the value .d. Observations excluded from the match using {inp:if}/{inp:in} are
	assigned the value .i. Observations excluded from the match due to missing value in {cmd:grpdummy()} are
	assigned the value .g. Observations excluded from the match due to missing value in {cmd:matchvar()} are
	assigned the value .m. All values have descreptive value labels.

{pstd}{hi:_matchID}{break}
	This variable indicates the ID of the target observations in each match pair/group. For matched
	target observations, the value in _matchID will be equal to the value in the ID
	variable. Since the values in the ID varaible are unique and there is exactly one target
	observation in each matched pair/group, this variable functions as a unique pair/group ID.
	In addition to indicating which observations are included in the same pair/group, this
	varaible can be used to include a pair/group fixed effect in a regression.

{pstd}{hi:_matchDiff}{break}
	This variable indicates the difference in {cmd:matchvar()} between matched base observations
	and target observations. In a one-to-one match this value is the identical for
	both the base observation and the target observation in each matched pair.
	In a many-to-one match, this value is only indicated for base observations. It is
	missing for target observations as there are potentially multiple matches, and
	subsequently multiple differences.

{pstd}{hi:_matchCount}{break}
	In a many-to-one match, this variable indicates how many base observations were
	matched towards each matched target observation. This variable can be used as regression
	weights when controlling for the fact that some observations are matched towards multiple
	observations.

{marker optslong}
{title:Options}

{phang}{cmdab:grp:dummy(}{it:varname}{cmd:)} is the dummy variable that indicates if an observation
	is a base or target observation. This variable, must be numeric and is only allowed to have
	the values 1, 0 or missing. 1 indicates a base observation, 0 indicates a target observation,
	and observations with a missing value will be excluded from the matching.

{phang}{cmdab:match:var(}{it:varname}{cmd:)} is the variable used to compare observations when
	matching. This must be a numeric variable, and it is typically a continuous
	variable. Observations with a missing value will be excluded from the matching.

{phang}{cmdab:id:var(}{it:varname}{cmd:)} indicates the variable that uniquely
	and fully identifies the data set. The values in this variable is the values
	that will be used in the variable that indicates which target observation each
	base observations matched against. If this option is omitted, a variable called
	_ID will be generated. The observation in the first row is given the value 1,
	the second row value 2 and so fourth.

{pmore}This command assumes only one ID variable as that is the best practice this command
	follows (see next paragraph for the exception of panel data sets). Here follows two
	suggested solutions if a data set this command will be used on has more than one ID
	variable. {bf:1.} Do not use the {cmd:idvar()} option and after the mathcing copy the mutliple
	ID variables yourself. {bf:2.} Combine your ID variables into one ID variable. Here are two
	examples on how that can be done (the examples below work just as well when combining more
	than two ID variables to one.):

{pmore2}{inp:egen }{it:new_ID_var }{inp:= group(}{it:old_ID_var1 old_ID_var2}{inp:)}

{pmore2}{inp:gen}{space 2}{it:new_ID_var }{inp:= }{it:old_ID_var1 }{inp:+ "_" + }{it:old_ID_var2}{space 4}//Works only with string vars

{pmore}Panel data sets are one of the few cases where multiple ID variables is good practice. However,
	in the case of matching it is unlikely that it is correct to include multiple time rounds for
	the same observation. That would lead to some base observations being matched to
	one target observation in the first round, and one another in the second. In impact
	evaluations, matchings are almost exclusively done only on the baseline data.

{phang}{cmdab:m1} sets the match to a many-to-one match (see {help iematch##desc:description}).
	This allows multiple base observations to be matched towards a single target observation.
	The default is the one-to-one match where a maximum one base observation is matched towards
	each target observation. This option allows the number of base observations
	to be larger then the number of target observations.

{phang}{cmdab:maxdiff(}{it:numlist}{cmd:)} sets a maximum allowed difference between
	a base observation and a target observation for a match to be valid. Any base
	observation without a valid match within this difference will end up unmatched.

{phang}{cmd:seedok} supresses the error message throwned when there are duplicates among
	the base observations or the target observations in {cmd:matchvar()}. When there
	are duplicates a random variable is used to distinguish which variable to match.
	Setting the seed makes this randomization replicable and thereby making the matching
	also replicable. The {help seed} should be set before this command by the user. When the
	seed is set, or if replicable matching is not important, then the option {cmd:seedok} can
	be used to supress the error message. Duplicate pairs where one observation is a base
	observation and the other is a target observations are allowed.

{phang}{cmdab:matchre:sultname(}{it:string}{cmd:)} manually sets the
	name of the variable that reports the matching result for each observation.
	If omitted, the default name is {inp:_matchResult}. The names {inp:_ID},
	{inp:_matchID}, {inp:_matchDiff} and {inp:_matchCount} are not allowed.

{phang}{cmdab:matchid:name(}{it:string}{cmd:)} manually sets the
	name of the variable that list the ID of the target observations in each match pair/group.
	If omitted, the default name is {inp:_matchID}. The names {inp:_ID}, {inp:_matchDiff}, {inp:_matchResult}
	and {inp:_matchCount} are not allowed.

{phang}{cmdab:matchdi:ffname(}{it:string}{cmd:)} manually sets the name of the variable
	that indicates the difference between the matched base observations
	and target observations. If omitted, the default name is {inp:_matchDiff}. The
	names {inp:_ID}, {inp:_matchID}, {inp:_matchResult} and {inp:_matchCount} are
	not allowed.

{phang}{cmdab:matchco:untname(}{it:string}{cmd:)} manually sets the
	name of the variable that indicates the number of base observations that has
	been matched towards each matched matched target observation. This option may
	only be used in combination with option {cmd:m1}. If omitted, the default
	name is {inp:_matchCount}. The names {inp:_ID}, {inp:_matchID}, {inp:_matchDiff}
	and {inp:_matchResult} are not allowed.

{title:Examples}

{pstd} {hi:Example 1.}

{pmore}{inp:iematch , grpdummy({it:tmt}) matchvar({it:p_hat})}

{pmore}In the example above, the observations with value 1 in {it:tmt} will be matched
	towards the nearest, in terms of {it:p_hat}, observations with value 0 in {it:tmt}.

{pstd} {hi:Example 2.}

{pmore}{inp:iematch if {it:baseline} == 1  , grpdummy({it:tmt}) matchvar({it:p_hat}) maxdiff(.001)}

{pmore}In the example above, the observations with value 1 in {it:tmt} will be matched
	towards the nearest, in terms of {it:p_hat}, observations with value 0 in {it:tmt} as
	long as the difference in {it:p_hat} is less than .001. Only observations that has the
	value 1 in variable {it:baseline} will be included in the match.

{title:Acknowledgements}

{phang}I would like to acknowledge the help in testing and proofreading I received in relation to this command and help file from (in alphabetic order):{p_end}
{pmore}Seungmin Lee{break}Mrijan Rimal{break}

{title:Author}

{phang}Kristoffer Bjarkefur, The World Bank, DECIE

{phang}Please send bug-reports, suggestions and requests for clarifications
		 writing "ietools iematch" in the subject line to:{break}
		 kbjarkefur@worldbank.org

{phang}You can also see the code, make comments to the code, see the version
		 history of the code, and submit additions or edits to the code through
		 the github repository of ietoolkit:{break}
		 {browse "https://github.com/worldbank/ietoolkit"}


Graph Range starting at 0 added

Graph Range starting at 0 added

Graph Range starting at 0 added

cap	program drop	ieimpgraph
	program define 	ieimpgraph
*	preserve
	syntax varlist, [TItle(string)]

	mat beta_ = e(b)

	local counter = 0
	local textfile = "Mrijan"
	local date = "$S_DATE"

	qui{

	foreach var of local varlist{
		cap assert inlist(`var',0,1) | missing(`var')
			if _rc {
				noi display as error "{phang} The variable `var' is not a dummy. Treatment variable needs to be a dummy(0 or 1) variable. {p_end}"
				noi display ""
				error 149
				}
			else {
				}

		local counter = `counter' + 1
		di `counter'

		scalar coeff_`var' = _b[`var']
		noi display coeff_`var'

		scalar coeff_se_`var' = _se[`var']
		noi display coeff_se_`var'

		count if e(sample) == 1 & `var' == 1 //Count one tmt group at the time
		scalar obs_`var' = r(N)
		noi display obs_`var'

	}

	local count: word count `varlist'
	local graphCount = `count' + 1
	//tokenize "`varlist'"
	//noi di `count'

	//Make all vars tempvars (maybe do later)
	//Make sure that missing is properly handled
	tempvar anyTMT
	egen `anyTMT' = rowmax(`varlist') if e(sample) == 1
	tempvar control
	gen `control' = (`anyTMT' == 0) if !missing(`anyTMT')

	noi sum `e(depvar)' if e(sample) == 1 & `control' == 1
	scalar ctl_N		= r(N)
	scalar ctl_mean	  	= r(mean)
	scalar ctl_mean_sd 	= r(sd)

		foreach var of local varlist {
			scalar  conf_int_min_`var'   =	coeff_`var'-(1.96*coeff_se_`var') + ctl_mean
			scalar  conf_int_max_`var'   =	coeff_`var'+(1.96*coeff_se_`var') + ctl_mean

			test `var'
			local star_`var' " "

			scalar  pvalue =r(p)
			if pvalue < 0.10 {
				local star_`var' "*"
			}
			if pvalue < 0.05 {
				local star_`var' "**"
			}
			if pvalue < 0.01 {
				local star_`var' "***"
			}
			noi display "`star_`var''"
			scalar tmt_mean_`var' = ctl_mean + coeff_`var'
		}

	tempname 	newHandle
	tempfile	newTextFile
	cap file close 	`newHandle'

	file open  	`newHandle' using "`newTextFile'", text write append
	file write `newHandle' ///
		"order" 	_tab "xLabeled"	_tab "mean" _tab "coeff" _tab "conf_int_min" _tab "conf_int_max" _tab "obs" _tab "star" _n 	///
		%9.3f (1) _tab "Control"  _tab %9.3f (ctl_mean)      _tab  		 			_tab 		 			  	  _tab 			 				_tab %9.3f (ctl_N) 	   _tab			  	  _n
	file close `newHandle'

	tempvar newCounter
	gen `newCounter' = 2
		foreach var in `varlist' {
			file open  	`newHandle' using "`newTextFile'", text write append
			file write `newHandle' ///
			%9.3f (`newCounter') _tab "`var'" _tab %9.3f (tmt_mean_`var') _tab  %9.3f (coeff_`var')  _tab %9.3f (conf_int_min_`var') _tab %9.3f (conf_int_max_`var') _tab %9.3f (obs_`var')   _tab "`star_`var''"  _n
			file close `newHandle'
			replace `newCounter' = `newCounter' + 1
			}

		copy "`newTextFile'"  "mainMasterDofile.txt" , replace

		insheet using mainMasterDofile.txt, clear

		if order == 1 local obsControl = obs
		local obsLabelControl = xlabeled[1]

		local starOption `" xlabel(1 " `obsLabelControl'(N=`obsControl')" "'
		*noi di "`starOption'" /

	forval x = 2/`graphCount' {

			list obs if order == `x'
			local obsTreat = obs[`x']

			local starTreat = star[`x']
			local starLabel = xlabeled[`x']

			local starOption `" `starOption' `x' " `starLabel' (N= `obsTreat')  `starTreat'" "'

		}

	local starOption `" `starOption' , noticks labsize(medsmall) ) "'
	/* noi di "Mrijan rimal"
	noi di `" "`starOption'"  "'
	noi di "Mrijan rimal" */

	local graphname gph_new
	local colourOption ""

	forval colourLoop = 1/`graphCount' {

		local colour

		noi di 0

		local colourNum = mod(`colourLoop', 5)

		if `colourNum' == 1 local colour = "215 25 28"
		if `colourNum' == 2 local colour = "253 174 93"
		if `colourNum' == 3 local colour = "255 255 191"
		if `colourNum' == 4 local colour = "171 217 233"
		if `colourNum' == 0 local colour = "43 123 182"

		noi di 1

		local colourOption `"`colourOption' (bar mean order if order == `colourLoop', color("`colour'") yscale(range(0)) ) "'

		noi di 2

		noi di `"`colourOption'"'

	}

	noi di 3

	local confIntGraph = "(rcap conf_int_max conf_int_min order, yscale(range(0)) lc(gs)) (scatter mean order,  msym(none)  mlabs(medium) mlabpos(10) mlabcolor(black)), "

	local orderOption = "legend(order("

	forval y = 1(1)`graphCount'{
		local orderOption  "`orderOption' `y'"
	}

	local orderOption "`orderOption' ))"

	noi di 4

	noi di `" graph twoway `colourOption' `confIntGraph' `orderOption' "'

	graph twoway `colourOption' `confIntGraph' `orderOption' `starOption' saving("newfile.gph", replace) title("`title'")

	noi di 5

	graph export graphname.png, replace
}
*restore
end

cap	program drop	ieimpgraph
	program define 	ieimpgraph
*	preserve
	syntax varlist, [TITle(string)]

	mat beta_ = e(b)

	local counter = 0
	local textfile = "Mrijan"
	local date = "$S_DATE"

	qui{

	foreach var of local varlist{
		cap assert inlist(`var',0,1) | missing(`var')
			if _rc {
				noi display as error "{phang} The variable `var' is not a dummy. Treatment variable needs to be a dummy(0 or 1) variable. {p_end}"
				noi display ""
				error 149
				}
			else {
				}

		local counter = `counter' + 1
		di `counter'

		scalar coeff_`var' = _b[`var']
		noi display coeff_`var'

		scalar coeff_se_`var' = _se[`var']
		noi display coeff_se_`var'

		count if e(sample) == 1 & `var' == 1 //Count one tmt group at the time
		scalar obs_`var' = r(N)
		noi display obs_`var'

	}

	local count: word count `varlist'
	local graphCount = `count' + 1
	//tokenize "`varlist'"
	//noi di `count'

	//Make all vars tempvars (maybe do later)
	//Make sure that missing is properly handled
	tempvar anyTMT
	egen `anyTMT' = rowmax(`varlist') if e(sample) == 1
	tempvar control
	gen `control' = (`anyTMT' == 0) if !missing(`anyTMT')

	noi sum `e(depvar)' if e(sample) == 1 & `control' == 1
	scalar ctl_N		= r(N)
	scalar ctl_mean	  	= r(mean)
	scalar ctl_mean_sd 	= r(sd)

		foreach var of local varlist {
			scalar  conf_int_min_`var'   =	coeff_`var'-(1.96*coeff_se_`var') + ctl_mean
			scalar  conf_int_max_`var'   =	coeff_`var'+(1.96*coeff_se_`var') + ctl_mean

			test `var'
			local star_`var' " "

			scalar  pvalue =r(p)
			if pvalue < 0.10 {
				local star_`var' "*"
			}
			if pvalue < 0.05 {
				local star_`var' "**"
			}
			if pvalue < 0.01 {
				local star_`var' "***"
			}
			noi display "`star_`var''"
			scalar tmt_mean_`var' = ctl_mean + coeff_`var'
		}

	tempname 	newHandle
	tempfile	newTextFile
	cap file close 	`newHandle'

	file open  	`newHandle' using "`newTextFile'", text write append
	file write `newHandle' ///
		"order" 	_tab "xLabeled"	_tab "mean" _tab "coeff" _tab "conf_int_min" _tab "conf_int_max" _tab "obs" _tab "star" _n 	///
		%9.3f (1) _tab "Control"  _tab %9.3f (ctl_mean)      _tab  		 			_tab 		 			  	  _tab 			 				_tab %9.3f (ctl_N) 	   _tab			  	  _n
	file close `newHandle'

	tempvar newCounter
	gen `newCounter' = 2
	foreach var in `varlist' {
		file open  	`newHandle' using "`newTextFile'", text write append
		file write `newHandle' ///
		%9.3f (`newCounter') _tab "`var'" _tab %9.3f (tmt_mean_`var') _tab  %9.3f (coeff_`var')  _tab %9.3f (conf_int_min_`var') _tab %9.3f (conf_int_max_`var') _tab %9.3f (obs_`var')   _tab "`star_`var''"  _n
		file close `newHandle'
		replace `newCounter' = `newCounter' + 1
		}

	copy "`newTextFile'"  "mainMasterDofile.txt" , replace

	insheet using mainMasterDofile.txt, clear

	if order == 1 local obsControl = obs
	local obsLabelControl = xlabeled[1]
	local starOption `" xlabel(1 " `obsLabelControl'(N=`obsControl')" "'
	*noi di "`starOption'" /

	forval x = 2/`graphCount' {
			noi di "Hello"
			list obs if order == `x'
			local obsTreat = obs[`x']
			local starTreat = star[`x']
			local starLabel = xlabeled[`x']
			local starOption `" `starOption' `x' " `starLabel' (N= `obsTreat')  `starTreat'" "'
			noi di "Hello2"
		}

	local starOption `" `starOption' , noticks labsize(medsmall) ) "'
	/* noi di "Mrijan rimal"
	noi di `" "`starOption'"  "'
	noi di "Mrijan rimal" */

	local graphname gph_new
	local colourOption ""

	forval colourLoop = 1/`graphCount' {

		local colour

		noi di 0

		local colourNum = mod(`colourLoop', 5)

		if `colourNum' == 1 local colour = "215 25 28"
		if `colourNum' == 2 local colour = "253 174 93"
		if `colourNum' == 3 local colour = "255 255 191"
		if `colourNum' == 4 local colour = "171 217 233"
		if `colourNum' == 0 local colour = "43 123 182"

		noi di 1

		local colourOption `"`colourOption' (bar mean order if order == `colourLoop', color("`colour'")) "'

		noi di 2

		noi di `"`colourOption'"'

	}

	noi di 3

	local confIntGraph = "(rcap conf_int_max conf_int_min order, lc(gs)) (scatter mean order, msym(none)  mlabs(medium) mlabpos(10) mlabcolor(black)), "

	local orderOption = "legend(order("

	forval y = 1(1)`graphCount'{
		local orderOption  "`orderOption' `y'"
	}

	local orderOption "`orderOption' ))"

	noi di 4

	noi di `" graph twoway `colourOption' `confIntGraph' `orderOption' "'

	graph twoway `colourOption' `confIntGraph' `orderOption' `starOption' saving("newfile.gph", replace) title("`title'")

	noi di 5

	graph export graphname.png, replace
}
*restore
end


Update Do_File_Results.do

Update Do_File_Results.do

/*
###############
Set Up:
###############

*/

clear
 cd "/Users/kevin/Desktop/PoliceAssaults"
 *No Federal Agencies, 0s if state had 0 for a year in assaults.
 insheet using "data/final/NonZero_NoFed_FinalData.csv"

 /*
 Other Options
 */
 /*
 *No Federal Agencies, but with NA's if states had 0 for a year in assaults.
 *insheet using "data/final/NoFed_FinalData.csv"
 *Federal Agencies, but with NA's if states had 0 for a year in assaults.
 insheet using "data/final/Fed_FinalData.csv"
 *Federal Agencies, 0s if state had 0 for a year in assaults.
 insheet using "data/final/NonZero_Fed_FinalData.csv"
 */
 *insheet using "data/final/FinalData_nofed2.csv"
 *insheet using "data/final/FinalData.csv"
 set more off

 run "do/variables.do"

 /*
 ###############
 Stata Time, Set Your TimeSeries
 ###############
 */
 xtset  stateName ov_correcttime

 *Drop Florida because it only reports in December (looks like full assaults).
 drop if state=="Florida"
 *Canal Zone and Puerto Rico and Virgin Islands have no assaults.
 drop if state=="Canal Zone"
 drop if state=="Puerto Rico"
 drop if state=="Virgin Islands"
 *drop if state=="Guam"
 *Did not report their crime rates properly.
 drop if state=="Alabama"
 drop if state=="Rhode Island"
 *DC only has One Purchase
 drop if state=="District of Columbia"
 drop if unemployrate==0
 drop if year==2015
 drop if year==2016

/*
####################################################################
*/
 count if ov_quantitybought > 0
 count if assaults != .
 count if assaults == 0

 tab state, nofreq
 display r(r)

 count if ov_quantitybought > 0
 count if assaults != .
 count if assaults == 0

 sum assaults
 sum vicrimepop
 sum popmillion
 sum officerper1000
 sum unemployrate
 sum black_perc
 sum lincome
 sum ov_clothing_quantity_hund
 sum ov_clothing_stockpile_hund
 sum ov_armor_quantity_hund
 sum ov_armor_stockpile_hund

 sum ov_weapons_stockpile_hund
 sum ov_record_quantity_hund
 sum ov_photo_stockpile_hund

 /*
 For Poster:

 Carriere, K. R., & Encinosa, W. (2017, June). The Militarization of Police: Evidence of Increased Citizen Conflict. Poster Presented at the Society for the Psychological Study of Social Issues Summer Conference, Albuquerque, NM.
 */
 /*
 sum ov_clothing_quantity
 sum ov_clothing_stockpile
 sum ov_armor_quantity
 sum ov_armor_stockpile
 sum ov_weapon_quantity
 sum ov_weapon_quantity_hund
 sum ov_photo_quantity
 sum ov_photo_stockpile

 xtnbreg assaults i.ov_correcttime c.l3_ov_clothing_stockpile_hund##c.l3_ov_clothing_stockpile_hund c.l3_ov_armor_stockpile_hund##c.l3_ov_armor_stockpile_hund c.l3_ov_weapons_stockpile_hund##c.l3_ov_weapons_stockpile_hund c.l3_ov_photo_stockpile_hund##c.l3_ov_photo_stockpile_hund  $controls, irr fe exposure(vicrimepop)
 margins, at(l3_ov_armor_stockpile_hund=(0(.25)21.5)) atmeans vsquish noatlegend
 marginsplot, plot1opts(mcolor("ltblue") msymbol("dh")) noci saving(file1, replace)
 xtnbreg assaultinjurytot i.ov_correcttime c.l6_ov_clothing_stockpile_hund##c.l6_ov_clothing_stockpile_hund c.l6_ov_armor_stockpile_hund##c.l6_ov_armor_stockpile_hund c.l6_ov_weapons_stockpile_hund##c.l6_ov_weapons_stockpile_hund c.l6_ov_photo_stockpile_hund##c.l6_ov_photo_stockpile_hund  $controls, irr fe exposure(vicrimepop)
margins, at(l6_ov_armor_stockpile_hund=(0(.25)21.5)) atmeans vsquish noatlegend
marginsplot, plot1opts(mcolor("cranberry") msymbol("sh")) noci saving(file2, replace)
 xtnbreg assaultinjurytot i.ov_correcttime c.l12_ov_clothing_stockpile_hund##c.l12_ov_clothing_stockpile_hund c.l12_ov_armor_stockpile_hund##c.l12_ov_armor_stockpile_hund c.l12_ov_weapons_stockpile_hund##c.l12_ov_weapons_stockpile_hund c.l12_ov_photo_stockpile_hund##c.l12_ov_photo_stockpile_hund  $controls, irr fe exposure(vicrimepop)
 margins, at(l12_ov_armor_stockpile_hund=(0(.25)21.5)) atmeans vsquish noatlegend
marginsplot, plot1opts(mcolor("midblue") msymbol("th")) noci saving(file3, replace)
combomarginsplot file1 file2 file3, ///
    labels("Three Month Lag" "Six Month Lag" "Twelve Month Lag") noci

marginsplot, plot1opts(mcolor("olive") lcolor("forest_green")) plot2opts(mcolor("khaki") lcolor("ltkhaki")) xtitle("Current Round") ytitle("Mean Amount Given to Partner") title("Model 1") noci
*/

/*
Table 1:
*/

pwcorr assaults vicrimepop popmillion officerper1000 unemployrate lincome black_perc l6_ov_clothing l6_ov_armor l6_ov_weapons l6_ov_photos, sig star(.05)

/*
Table 2:
Negative Binomials with 6 Month Lag
*/
xtnbreg assaultinjurytot i.ov_correcttime c.l6_ov_clothing_hund  c.l6_ov_armor_hund c.l6_ov_weapons_hund c.l6_ov_photos_hund $controls, irr fe exposure(vicrimepop)
xtnbreg assaultinjurytot i.ov_correcttime c.l6_ov_clothing_stockpile_hund c.l6_ov_armor_stockpile_hund c.l6_ov_weapons_stockpile_hund c.l6_ov_photo_stockpile_hund  $controls, irr fe exposure(vicrimepop)
xtnbreg assaultinjurytot i.ov_correcttime c.l6_ov_clothing_stockpile_hund##c.l6_ov_clothing_stockpile_hund c.l6_ov_armor_stockpile_hund##c.l6_ov_armor_stockpile_hund c.l6_ov_weapons_stockpile_hund##c.l6_ov_weapons_stockpile_hund c.l6_ov_photo_stockpile_hund##c.l6_ov_photo_stockpile_hund  $controls, irr fe exposure(vicrimepop)

/*
Table 3:
Negative Binomials with 12 Month Lag
*/
xtnbreg assaultinjurytot i.ov_correcttime c.l12_ov_clothing_hund  c.l12_ov_armor_hund c.l12_ov_weapons_hund c.l12_ov_photos_hund $controls, irr fe exposure(vicrimepop)
xtnbreg assaultinjurytot i.ov_correcttime c.l12_ov_clothing_stockpile_hund c.l12_ov_armor_stockpile_hund c.l12_ov_weapons_stockpile_hund c.l12_ov_photo_stockpile_hund $controls, irr fe exposure(vicrimepop)
xtnbreg assaultinjurytot i.ov_correcttime c.l12_ov_clothing_stockpile_hund##c.l12_ov_clothing_stockpile_hund c.l12_ov_armor_stockpile_hund##c.l12_ov_armor_stockpile_hund c.l12_ov_weapons_stockpile_hund##c.l12_ov_weapons_stockpile_hund c.l12_ov_photo_stockpile_hund##c.l12_ov_photo_stockpile_hund  $controls, irr fe exposure(vicrimepop)
/*
Table 4:
Negative Binomials with 3 Month Lag
*/
xtnbreg assaultinjurytot i.ov_correcttime c.l3_ov_clothing_hund  c.l3_ov_armor_hund c.l3_ov_weapons_hund c.l3_ov_photos_hund $controls, irr fe exposure(vicrimepop)
xtnbreg assaultinjurytot i.ov_correcttime c.l3_ov_clothing_stockpile_hund c.l3_ov_armor_stockpile_hund c.l3_ov_weapons_stockpile_hund c.l3_ov_photo_stockpile_hund  $controls, irr fe exposure(vicrimepop)
xtnbreg assaults i.ov_correcttime c.l3_ov_clothing_stockpile_hund##c.l3_ov_clothing_stockpile_hund c.l3_ov_armor_stockpile_hund##c.l3_ov_armor_stockpile_hund c.l3_ov_weapons_stockpile_hund##c.l3_ov_weapons_stockpile_hund c.l3_ov_photo_stockpile_hund##c.l3_ov_photo_stockpile_hund  $controls, irr fe exposure(vicrimepop)

/*
Other variables you're welcome to try:

Mean-centered everything with variables that have _c in them.

/*
###############
Set Up:
###############

*/

clear
 cd "/Users/kevin/Desktop/PoliceAssaults"
 *No Federal Agencies, 0s if state had 0 for a year in assaults.
 insheet using "data/final/NonZero_NoFed_FinalData.csv"

 /*
 Other Options
 */
 /*
 *No Federal Agencies, but with NA's if states had 0 for a year in assaults.
 *insheet using "data/final/NoFed_FinalData.csv"
 *Federal Agencies, but with NA's if states had 0 for a year in assaults.
 insheet using "data/final/Fed_FinalData.csv"
 *Federal Agencies, 0s if state had 0 for a year in assaults.
 insheet using "data/final/NonZero_Fed_FinalData.csv"
 */
 *insheet using "data/final/FinalData_nofed2.csv"
 *insheet using "data/final/FinalData.csv"
 set more off

 run "do/variables.do"

 /*
 ###############
 Stata Time, Set Your TimeSeries
 ###############
 */
 xtset  stateName ov_correcttime

 *Drop Florida because it only reports in December (looks like full assaults).
 drop if state=="Florida"
 *Canal Zone and Puerto Rico and Virgin Islands have no assaults.
 drop if state=="Canal Zone"
 drop if state=="Puerto Rico"
 drop if state=="Virgin Islands"
 *drop if state=="Guam"
 *Did not report their crime rates properly.
 drop if state=="Alabama"
 drop if state=="Rhode Island"
 *DC only has One Purchase
 drop if state=="District of Columbia"
 drop if unemployrate==0
 drop if year==2015
 drop if year==2016

/*
####################################################################
*/
 count if ov_quantitybought > 0
 count if assaults != .
 count if assaults == 0

 tab state, nofreq
 display r(r)

 count if ov_quantitybought > 0
 count if assaults != .
 count if assaults == 0

 sum assaults
 sum vicrimepop
 sum popmillion
 sum officerper1000
 sum unemployrate
 sum black_perc
 sum lincome
 sum ov_clothing_quantity_hund
 sum ov_clothing_stockpile_hund
 sum ov_armor_quantity_hund
 sum ov_armor_stockpile_hund

 sum ov_weapons_stockpile_hund
 sum ov_record_quantity_hund
 sum ov_photo_stockpile_hund

 /*
 For Poster:

 Carriere, K. R., & Encinosa, W. (2017, June). The Militarization of Police: Evidence of Increased Citizen Conflict. Poster Presented at the Society for the Psychological Study of Social Issues Summer Conference, Alberqueque, NM.
 */
 /*
 sum ov_clothing_quantity
 sum ov_clothing_stockpile
 sum ov_armor_quantity
 sum ov_armor_stockpile
 sum ov_weapon_quantity
 sum ov_weapon_quantity_hund
 sum ov_photo_quantity
 sum ov_photo_stockpile

 xtnbreg assaults i.ov_correcttime c.l3_ov_clothing_stockpile_hund##c.l3_ov_clothing_stockpile_hund c.l3_ov_armor_stockpile_hund##c.l3_ov_armor_stockpile_hund c.l3_ov_weapons_stockpile_hund##c.l3_ov_weapons_stockpile_hund c.l3_ov_photo_stockpile_hund##c.l3_ov_photo_stockpile_hund  $controls, irr fe exposure(vicrimepop)
 margins, at(l3_ov_armor_stockpile_hund=(0(.25)21.5)) atmeans vsquish noatlegend
 marginsplot, plot1opts(mcolor("ltblue") msymbol("dh")) noci saving(file1, replace)
 xtnbreg assaultinjurytot i.ov_correcttime c.l6_ov_clothing_stockpile_hund##c.l6_ov_clothing_stockpile_hund c.l6_ov_armor_stockpile_hund##c.l6_ov_armor_stockpile_hund c.l6_ov_weapons_stockpile_hund##c.l6_ov_weapons_stockpile_hund c.l6_ov_photo_stockpile_hund##c.l6_ov_photo_stockpile_hund  $controls, irr fe exposure(vicrimepop)
margins, at(l6_ov_armor_stockpile_hund=(0(.25)21.5)) atmeans vsquish noatlegend
marginsplot, plot1opts(mcolor("cranberry") msymbol("sh")) noci saving(file2, replace)
 xtnbreg assaultinjurytot i.ov_correcttime c.l12_ov_clothing_stockpile_hund##c.l12_ov_clothing_stockpile_hund c.l12_ov_armor_stockpile_hund##c.l12_ov_armor_stockpile_hund c.l12_ov_weapons_stockpile_hund##c.l12_ov_weapons_stockpile_hund c.l12_ov_photo_stockpile_hund##c.l12_ov_photo_stockpile_hund  $controls, irr fe exposure(vicrimepop)
 margins, at(l12_ov_armor_stockpile_hund=(0(.25)21.5)) atmeans vsquish noatlegend
marginsplot, plot1opts(mcolor("midblue") msymbol("th")) noci saving(file3, replace)
combomarginsplot file1 file2 file3, ///
    labels("Three Month Lag" "Six Month Lag" "Twelve Month Lag") noci

marginsplot, plot1opts(mcolor("olive") lcolor("forest_green")) plot2opts(mcolor("khaki") lcolor("ltkhaki")) xtitle("Current Round") ytitle("Mean Amount Given to Partner") title("Model 1") noci
*/

/*
Table 1:
*/

pwcorr assaults vicrimepop popmillion officerper1000 unemployrate lincome black_perc l6_ov_clothing l6_ov_armor l6_ov_weapons l6_ov_photos, sig star(.05)

/*
Table 2:
Negative Binomials with 6 Month Lag
*/
xtnbreg assaultinjurytot i.ov_correcttime c.l6_ov_clothing_hund  c.l6_ov_armor_hund c.l6_ov_weapons_hund c.l6_ov_photos_hund $controls, irr fe exposure(vicrimepop)
xtnbreg assaultinjurytot i.ov_correcttime c.l6_ov_clothing_stockpile_hund c.l6_ov_armor_stockpile_hund c.l6_ov_weapons_stockpile_hund c.l6_ov_photo_stockpile_hund  $controls, irr fe exposure(vicrimepop)
xtnbreg assaultinjurytot i.ov_correcttime c.l6_ov_clothing_stockpile_hund##c.l6_ov_clothing_stockpile_hund c.l6_ov_armor_stockpile_hund##c.l6_ov_armor_stockpile_hund c.l6_ov_weapons_stockpile_hund##c.l6_ov_weapons_stockpile_hund c.l6_ov_photo_stockpile_hund##c.l6_ov_photo_stockpile_hund  $controls, irr fe exposure(vicrimepop)

/*
Table 3:
Negative Binomials with 12 Month Lag
*/
xtnbreg assaultinjurytot i.ov_correcttime c.l12_ov_clothing_hund  c.l12_ov_armor_hund c.l12_ov_weapons_hund c.l12_ov_photos_hund $controls, irr fe exposure(vicrimepop)
xtnbreg assaultinjurytot i.ov_correcttime c.l12_ov_clothing_stockpile_hund c.l12_ov_armor_stockpile_hund c.l12_ov_weapons_stockpile_hund c.l12_ov_photo_stockpile_hund $controls, irr fe exposure(vicrimepop)
xtnbreg assaultinjurytot i.ov_correcttime c.l12_ov_clothing_stockpile_hund##c.l12_ov_clothing_stockpile_hund c.l12_ov_armor_stockpile_hund##c.l12_ov_armor_stockpile_hund c.l12_ov_weapons_stockpile_hund##c.l12_ov_weapons_stockpile_hund c.l12_ov_photo_stockpile_hund##c.l12_ov_photo_stockpile_hund  $controls, irr fe exposure(vicrimepop)
/*
Table 4:
Negative Binomials with 3 Month Lag
*/
xtnbreg assaultinjurytot i.ov_correcttime c.l3_ov_clothing_hund  c.l3_ov_armor_hund c.l3_ov_weapons_hund c.l3_ov_photos_hund $controls, irr fe exposure(vicrimepop)
xtnbreg assaultinjurytot i.ov_correcttime c.l3_ov_clothing_stockpile_hund c.l3_ov_armor_stockpile_hund c.l3_ov_weapons_stockpile_hund c.l3_ov_photo_stockpile_hund  $controls, irr fe exposure(vicrimepop)
xtnbreg assaults i.ov_correcttime c.l3_ov_clothing_stockpile_hund##c.l3_ov_clothing_stockpile_hund c.l3_ov_armor_stockpile_hund##c.l3_ov_armor_stockpile_hund c.l3_ov_weapons_stockpile_hund##c.l3_ov_weapons_stockpile_hund c.l3_ov_photo_stockpile_hund##c.l3_ov_photo_stockpile_hund  $controls, irr fe exposure(vicrimepop)

/*
Other variables you're welcome to try:

Mean-centered everything with variables that have _c in them.


comment

comment

use "/Users/braddv/Desktop/BERNIE/employamericansnow/bernie10-egen.dta", clear
gen runningwt = 0
gen prevwt = 0
save "/Users/braddv/Desktop/BERNIE/employamericansnow/bernie5-1.dta", replace
keep if familyheadyouthdisadvantaged
bysort statefip puma: gen pumaid = _n
bysort statefip puma (headmaxyouthempp): replace runningwt = sum(perwt)
//use (headmaxyouthempp) or (invheadmaxyouthempp) above depending if you want max or min likelihood
replace prevwt = runningwt - perwt if runningwt > numjobspuma
gen jobsleft = numjobspuma - prevwt
replace jobsleft = 0 if jobsleft < 0
replace jobsleft = 0 if runningwt < jobsleft
gen jobrecipient = 0
replace jobrecipient = 1 if runningwt < numjobspuma | jobsleft > 0
keep serial pernum jobrecipient jobsleft
joinby serial pernum using "/Users/braddv/Desktop/BERNIE/employamericansnow/bernie5-1.dta", unmatched(both)

replace jobrecipient = 0 if missing(jobrecipient)
replace jobsleft = 0 if missing(jobsleft)

gen newperwt = perwt
egen maxrunningwt = max(runningwt), by(statefip puma)

expand 2 if jobsleft > 0, generate(duplicate)
replace newperwt = int(jobsleft) if duplicate == 1
replace newperwt = max(int(perwt-jobsleft),0) if duplicate == 0 & jobsleft > 0
replace jobrecipient = 0 if duplicate == 0 & jobsleft > 0

egen jobsreceived = sum(jobrecipient*newperwt)

gen job_money = 0
replace job_money = 10500 if jobrecipient

gen numjobsafter = numjobspuma
replace numjobsafter = maxrunningwt if maxrunningwt < numjobspuma

gen familyincome = ftotinc

gen newincome = familyincome+job_money

gen outofpov = (ftotinc <= povline) & (newincome > povline) & (newincome < 9999999)

egen outofpovfam = max(outofpov), by(serial famunit)

*sgini newincome if familyhead == 1 & familyincome < 9999999 [fweight=newperwt]
*sgini familyincome if familyhead == 1 & familyincome < 9999999 [fweight=newperwt]

gen povgap = povline - familyincome if familyincome < povline
gen newpovgap = povline - newincome if newincome < povline

gen poor = familyincome < povline
gen newpoor = newincome < povline

tab poor [fweight=newperwt]
tab newpoor [fweight=newperwt]

egen moneyspent = sum(job_money*newperwt) if jobrecipient
disp moneyspent[1]

tabulate job_money if familyhead [fweight=newperwt]

egen totalfam = sum(newperwt) if familyhead == 1
egen p0 = sum(newperwt) if poor & familyhead == 1
egen newp0 = sum(newperwt) if newpoor & familyhead == 1

egen p1 = sum((povgap*newperwt)/povline) if familyhead == 1
disp p1/totalfam
egen newp1 = sum((newpovgap*newperwt)/povline) if familyhead == 1
disp newp1/totalfam

egen p2 = sum((povgap/povline)^2*newperwt) if familyhead == 1
egen newp2 = sum((newpovgap/povline)^2*newperwt) if familyhead == 1

disp p2[7]/totalfam[7]
disp newp2[7]/totalfam[7]

bysort sex: tab jobrecipient [fweight=newperwt]
bysort racesing: tab jobrecipient [fweight=newperwt]
bysort finccut: tab jobrecipient [fweight=newperwt]
bysort educ: tab jobrecipient [fweight=newperwt]

use "/Users/braddv/Desktop/BERNIE/employamericansnow/bernie10-egen.dta", clear
gen runningwt = 0
gen prevwt = 0
save "/Users/braddv/Desktop/BERNIE/employamericansnow/bernie5-1.dta", replace
keep if familyheadyouthdisadvantaged
bysort statefip puma: gen pumaid = _n
bysort statefip puma (invheadmaxyouthempp): replace runningwt = sum(perwt)
replace prevwt = runningwt - perwt if runningwt > numjobspuma
gen jobsleft = numjobspuma - prevwt
replace jobsleft = 0 if jobsleft < 0
replace jobsleft = 0 if runningwt < jobsleft
gen jobrecipient = 0
replace jobrecipient = 1 if runningwt < numjobspuma | jobsleft > 0
keep serial pernum jobrecipient jobsleft
joinby serial pernum using "/Users/braddv/Desktop/BERNIE/employamericansnow/bernie5-1.dta", unmatched(both)

replace jobrecipient = 0 if missing(jobrecipient)
replace jobsleft = 0 if missing(jobsleft)

gen newperwt = perwt
egen maxrunningwt = max(runningwt), by(statefip puma)

expand 2 if jobsleft > 0, generate(duplicate)
replace newperwt = int(jobsleft) if duplicate == 1
replace newperwt = max(int(perwt-jobsleft),0) if duplicate == 0 & jobsleft > 0
replace jobrecipient = 0 if duplicate == 0 & jobsleft > 0

egen jobsreceived = sum(jobrecipient*newperwt)

gen job_money = 0
replace job_money = 10500 if jobrecipient

gen numjobsafter = numjobspuma
replace numjobsafter = maxrunningwt if maxrunningwt < numjobspuma

gen familyincome = ftotinc

gen newincome = familyincome+job_money

gen outofpov = (ftotinc <= povline) & (newincome > povline) & (newincome < 9999999)

egen outofpovfam = max(outofpov), by(serial famunit)

*sgini newincome if familyhead == 1 & familyincome < 9999999 [fweight=newperwt]
*sgini familyincome if familyhead == 1 & familyincome < 9999999 [fweight=newperwt]

gen povgap = povline - familyincome if familyincome < povline
gen newpovgap = povline - newincome if newincome < povline

gen poor = familyincome < povline
gen newpoor = newincome < povline

tab poor [fweight=newperwt]
tab newpoor [fweight=newperwt]

egen moneyspent = sum(job_money*newperwt) if jobrecipient
disp moneyspent[1]

tabulate job_money if familyhead [fweight=newperwt]

egen totalfam = sum(newperwt) if familyhead == 1
egen p0 = sum(newperwt) if poor & familyhead == 1
egen newp0 = sum(newperwt) if newpoor & familyhead == 1

egen p1 = sum((povgap*newperwt)/povline) if familyhead == 1
disp p1/totalfam
egen newp1 = sum((newpovgap*newperwt)/povline) if familyhead == 1
disp newp1/totalfam

egen p2 = sum((povgap/povline)^2*newperwt) if familyhead == 1
egen newp2 = sum((newpovgap/povline)^2*newperwt) if familyhead == 1

disp p2[7]/totalfam[7]
disp newp2[7]/totalfam[7]

bysort sex: tab jobrecipient [fweight=newperwt]
bysort racesing: tab jobrecipient [fweight=newperwt]
bysort finccut: tab jobrecipient [fweight=newperwt]


to.do:  some entries

to.do:  some entries

= to.do: =

o Some dotfiles, e.g. .gitconfig, really need to be modified by a script rather than
  simply symlinked.  That's because things like username and email address change from one
  system to another.  So use a file full of, e.g., git config --global ...  An alternative
  would be to include them.

o regular dotfiles should start with "_" rather than ".", to make them visible.

==============================================================================
Work Log:
========

==============================================================================
Local Variables:
    fill-column:90
End:


added user level vars

added user level vars

program kingcounty

makedata
makedv_county
balancepanel_county

end

program run_reg

sort unitid month
format firstm %tm

gen treat = (fips=="06047")
keep if treat == 1

bysort istiger month: egen newadded = total(month==firstmonth)
bysort istiger month: egen numupdated = total(numchanges>0)
bysort istiger month: egen avgattr = mean(hasattr)
bysort istiger month: egen avguser = mean(numusers)
bysort istiger month: egen avgowner = mean(numowner)
bysort istiger month: egen totowner = total(numowner)
bysort istiger month: egen didowner = total((numowner>0))

bysort istiger month: gen tag = (_n==1)

gen newa_tiger = sum(newadd * (istiger==1)*(tag==1))
gen newa_control = sum(newadd * (istiger==0)*(tag==1))
gen newa_sum = .
replace newa_sum = newa_tiger if ist == 1
replace newa_sum = newa_control if ist == 0
drop newa_ti newa_cont

gen percentupdated = numupd / newa_sum

list newadd newa_ numupd month istiger if month == 621 & tag == 1

local var didown
local var avgown
local var totown
local var newa
local var newa_sum
local var numupd
local var avgattr
local var percentup

replace `var' = 10 if `var' > 10

tw (connected `var' month if istiger == 0 & tag==1) (connected `var' month if istiger == 1 &tag==1), legend(order(2 "TIGER Counties" 1 "Control Counties" ))

graph export ${tables}tmp1.eps, replace

codebook

end

program makedv_county

**use ${stash}king_tmp, clear
use ${stash}ca_tmp, clear

keep if highwayclass == 3

**bysort highwayid: egen mixtiger = mean(istiger)

bysort highwayid month: gen numchanges = _N
bysort highwayid month: egen maxattrib = max(hasattrib)
bysort highwayid: gen firstmonth = month[1]
bysort highwayid: gen firstuser = user[1]
bysort highwayid month: egen numowner = total(firstuser==user)

bysort highwayid month user: gen tmp = (_n==1)
bysort highwayid month: egen numusers = total(tmp)
drop tmp

end

program balancepanel_county

bysort highwayid month: drop if _n > 1
drop unitid
gen unitid = highwayid

tsset unitid month
tsfill, full

local outcomes "numchanges maxattrib numowner numusers"

foreach x in `outcomes'{
    replace `x' = 0 if `x' == .
}

local covars "istiger firstmonth name hasattr fips"

foreach x in `covars'{
    gsort unitid month
    bysort unitid: carryforward `x', gen(tmp1)
    gsort unitid -month
    bysort unitid: carryforward tmp1, gen(tmp2)
    replace `x' = tmp2
    drop tmp1 tmp2
    di "finished `x'"
    di "---"
}

end

program makedata

use ${stash}mergemaster_way, clear

// control: fresno == 06019
// control: santa clara = 06085 / 1.8 million

// control: madera = 06039
// treat : merced = 06047

// treat: stanislaus = 06099
// treat: san joaquin = 06077 / pop 702k

keep if (fips == "06039" | fips == "06047")

egen highwayid = group(name)
replace highwayid = . if ishighway == 0
replace highwayid = . if name == "NA"
drop if highwayid == .

**save ${stash}king_tmp, replace
save ${stash}ca_tmp, replace

end

program kingcounty

makedata
makedv_county
balancepanel_county

end

program run_reg

sort unitid month
format firstm %tm

bysort istiger month: egen newadded = total(month==firstmonth)
bysort istiger month: egen numupdated = total(numchanges>0)
bysort istiger month: egen avgattr = mean(hasattr)

bysort istiger month: gen tag = (_n==1)

gen newa_tiger = sum(newadd * (istiger==1)*(tag==1))
gen newa_control = sum(newadd * (istiger==0)*(tag==1))
gen newa_sum = .
replace newa_sum = newa_tiger if ist == 1
replace newa_sum = newa_control if ist == 0
drop newa_ti newa_cont

gen percentupdated = numupd / newa_sum

list newadd newa_ numupd month istiger if month == 621 & tag == 1

local var newa
local var newa_sum
local var numupd
local var avgattr
local var percentup

replace `var' = 1200 if `var' > 1200

tw (connected `var' month if istiger == 0 & tag==1) (connected `var' month if istiger == 1 &tag==1), legend(order(2 "TIGER Counties" 1 "Control Counties" ))

graph export ${tables}tmp1.eps, replace

codebook

end

program makedv_county

**use ${stash}king_tmp, clear
use ${stash}ca_tmp, clear

keep if highwayclass == 3

**bysort highwayid: egen mixtiger = mean(istiger)

bysort highwayid month: gen numchanges = _N
bysort highwayid month: egen maxattrib = max(hasattrib)
bysort highwayid: gen firstmonth = month[1]

end

program balancepanel_county

bysort highwayid month: drop if _n > 1
drop unitid
gen unitid = highwayid

tsset unitid month
tsfill, full

local outcomes "numchanges maxattrib"

foreach x in `outcomes'{
    replace `x' = 0 if `x' == .
}

local covars "istiger firstmonth name hasattr"

foreach x in `covars'{
    gsort unitid month
    bysort unitid: carryforward `x', gen(tmp1)
    gsort unitid -month
    bysort unitid: carryforward tmp1, gen(tmp2)
    replace `x' = tmp2
    drop tmp1 tmp2
    di "finished `x'"
    di "---"
}

end

program makedata

use ${stash}mergemaster_way, clear

// control: fresno == 06019
// control: santa clara = 06085 / 1.8 million

// control: madera = 06039
// treat : merced = 06047

// treat: stanislaus = 06099
// treat: san joaquin = 06077 / pop 702k

keep if (fips == "06039" | fips == "06047")

egen highwayid = group(name)
replace highwayid = . if ishighway == 0
replace highwayid = . if name == "NA"
drop if highwayid == .

**save ${stash}king_tmp, replace
save ${stash}ca_tmp, replace

end