divide jobs among houses

divide jobs among houses

* the world is crumbling. solutions are being introduced. they wont pass without radical political change
* 1 billion divided equally between states
* 1 billion distributed on the basis of relative 16-25 y/o compared to total in all states
* 1 billion on relative unemployed compared to toal in all states
* 1 billion on the basis of the rleative # disadvantaged youth compared to total in all states

*STEPS:
* # of 16-25 y/o's per state
* total # of 16-25 y/os
* # of unemployed per state
* total # unemployed
* # disdvantaged youth
* total # disadvantaged youth

*then by puma w/in state
*
*tabulate age if statefip == 06 & puma == 3703 [fweight=perwt]
drop if year == 2013

gen youth = (age <= 25 & age >= 16)
gen disadvantaged = (poverty <= 100)
gen disadvantaged_youth = (youth & disadvantaged)
gen unemployed = (empstat == 2)
gen unemployedyouth = youth & unemployed

egen youth_in_hh = max(youth), by(serial)
egen unemployed_in_hh = max(unemployed), by(serial)
egen disadvantaged_hh = max(disadvantaged_youth), by(serial)

egen youth_state = total(perwt * youth), by(statefip)
egen youth_puma = total(perwt * youth), by(statefip puma)
*sum youth_puma if statefip == 06 & puma == 3703
*25371 youth in lancaster
gen youth_percentage = youth_puma / youth_state

egen unemployed_state = total(perwt * unemployed), by(statefip)
egen unemployed_puma = total(perwt * unemployed), by(statefip puma)

gen unemployed_percentage = unemployed_puma / unemployed_state

egen unemployed_youth_state = total(perwt * unemployedyouth), by(statefip)

*sum youth_puma if statefip == 06 & puma == 3703
*5797 youth in lancaster

egen disadvantaged_state = total(perwt * disadvantaged_youth), by(statefip)
egen disadvantaged_puma = total(perwt * disadvantaged_youth), by(statefip puma)

gen disadvantaged_percentage = disadvantaged_puma / disadvantaged_state

egen youth_total = total(perwt * youth)
egen unemployed_total = total(perwt * unemployed)
egen disadvantaged_total = total(perwt * disadvantaged_youth)

gen youth_percentage_state = youth_state/youth_total
gen unemployed_percentage_state = unemployed_state/unemployed_total
gen disadvantaged_percentage_state = disadvantaged_state/disadvantaged_total

gen state_money = 1000 * .02 + 1000 * youth_percentage_state + 1000 * unemployed_percentage_state + 1000 * disadvantaged_percentage_state

egen npumas = nvals(puma), by(statefip)

gen puma_money = (state_money/3) * (youth_percentage + unemployed_percentage + disadvantaged_percentage)
gen numjobspuma = puma_money / .0105 //.0105 is a 10,500 dollar per yr job ($15*30hrs*12weeks in summer and $15*10hrs*34weeks in schoolyr)
//alternatively, could be doled out as 48 weeks of $15/hr pay 15 hrs a week
gen numjobsstate = state_money / .0105

*figure out households w/ youth in them
egen householdwithyouth = max(youth), by(serial)
*youth hh's living in poverty
gen youthinpov = (householdwithyouth & (poverty <= 100) & pernum == 1)
tab youthinpov if pernum == 1 [fweight = perwt]
*162 jobs for 5287 households
save "/Users/braddv/Desktop/BERNIE/employamericansnow/bernie5-1.dta", replace
keep if youthinpov
bysort statefip puma: gen runningwt = sum(hhwt)
keep serial pernum runningwt
joinby serial pernum using "/Users/braddv/Desktop/BERNIE/employamericansnow/bernie5-1.dta", unmatched(both)
gen jobsleft = 0
gen prevwt = 0
replace prevwt = runningwt - hhwt if runningwt > numjobspuma
replace jobsleft = numjobspuma - prevwt if (prevwt < numjobspuma & prevwt > 0)
gen newhhwt = hhwt
expand 2 if jobsleft > 0, generate(duplicate)
replace newhhwt = jobsleft if duplicate == 1
replace newhhwt = hhwt-jobsleft if duplicate == 0

gen job_money = 0
replace job_money = 10500 if (runningwt < numjobspuma) | (jobsleft > 0 & duplicate == 1)

gen familyincome = inctot
replace familyincome = ftotinc if ftotinc < 9999999
replace familyincome = 0 if familyincome < 0

gen newincome = familyincome+job_money

gen povline = 11670 + (numprec-1)*4060
gen outofpov = disadvantaged & (newincome > povline) & (newincome < 9999999)

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

sgini newincome if pernum == 1 & familyincome < 9999999 [fweight=newhhwt]
sgini familyincome if pernum == 1 & familyincome < 9999999 [fweight=newhhwt]

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

egen totalhh = sum(newhhwt) if pernum == 1
egen p0 = sum(newhhwt) if poverty < 100 & pernum == 1

egen p1 = sum((povgap*newhhwt)/povline)
disp p1/totalhh
//.22842
egen newp1 = sum((newpovgap*newhhwt)/povline)
disp newp1/totalhh
//.19363

egen p2 = sum((povgap/povline)^2*newhhwt)
egen newp2 = sum((newpovgap/povline)^2*newhhwt)

disp p2/totalhh
//.1659
disp newp2/totalhh
//.1356

disp p0[23]/totalhh
//.19710145

egen newp0 = sum(newhhwt) if ((poverty < 100 & pernum == 1) & !(outofpov == 1 & pernum == 1))
disp newp0[23]/totalhh
//.1978997

egen totalhhstate = sum(newhhwt) if pernum == 1, by(statefip)
egen p0state = sum(newhhwt) if poverty < 100 & pernum == 1, by(statefip)
egen newp0state = sum(newhhwt) if ((poverty < 100 & pernum == 1) & !(outofpov == 1 & pernum == 1)), by(statefip)

/*. keep if youthinpov
(2,915,463 observations deleted)

. bysort statefip puma: gen runningwt = sum(hhwt)

. keep serial pernum runningwt

. joinby serial pernum using "/Users/braddv/Desktop/BERNIE/employamericansnow/bernie4-11.dta", unmatched(both)
*/

/* collapse (mean) state_money, by(statefip)
. export delimited using "/Users/braddv/Desktop/BERNIE/state_money.csv",
how to collapse without losing data? or i guess just use file again.
*/
//tab occ2010 if statefip==06 & youth [fweight=perwt] (california young jobs distribution)
//
/*collapse (mean) youth_state, by(statefip)
export delimited using "/Users/braddv/Desktop/BERNIE/youth_state.csv"*/
/*collapse (mean) disadvantaged_state, by(statefip)
export delimited using "/Users/braddv/Desktop/BERNIE/disadvantaged_state.csv"*/
/*collapse (mean) unemployed_state, by(statefip)
export delimited using "/Users/braddv/Desktop/BERNIE/unemployed_state.csv"*/
/*collapse (mean) unemployed_youth_state, by(statefip)
export delimited using "/Users/braddv/Desktop/BERNIE/unemployed_youth_state.csv"*/
/*collapse (mean) numjobsstate, by(statefip)
export delimited using "/Users/braddv/Desktop/BERNIE/numjobs_state.csv"*/

//tab job_money if pernum == 1 [fweight = hhwt]

* the world is crumbling. solutions are being introduced. they wont pass without radical political change
* 1 billion divided equally between states
* 1 billion distributed on the basis of relative 16-25 y/o compared to total in all states
* 1 billion on relative unemployed compared to toal in all states
* 1 billion on the basis of the rleative # disadvantaged youth compared to total in all states

*STEPS:
* # of 16-25 y/o's per state
* total # of 16-25 y/os
* # of unemployed per state
* total # unemployed
* # disdvantaged youth
* total # disadvantaged youth

*then by puma w/in state
*
*tabulate age if statefip == 06 & puma == 3703 [fweight=perwt]
drop if year == 2013

gen youth = (age <= 25 & age >= 16)
gen disadvantaged = (poverty <= 100)
gen disadvantaged_youth = (youth & disadvantaged)
gen unemployed = (empstat == 2)
gen unemployedyouth = youth & unemployed

egen youth_in_hh = max(youth), by(serial)
egen unemployed_in_hh = max(unemployed), by(serial)
egen disadvantaged_hh = max(disadvantaged_youth), by(serial)

egen youth_state = total(perwt * youth), by(statefip)
egen youth_puma = total(perwt * youth), by(statefip puma)
*sum youth_puma if statefip == 06 & puma == 3703
*25371 youth in lancaster
gen youth_percentage = youth_puma / youth_state

egen unemployed_state = total(perwt * unemployed), by(statefip)
egen unemployed_puma = total(perwt * unemployed), by(statefip puma)

gen unemployed_percentage = unemployed_puma / unemployed_state

egen unemployed_youth_state = total(perwt * unemployedyouth), by(statefip)

*sum youth_puma if statefip == 06 & puma == 3703
*5797 youth in lancaster

egen disadvantaged_state = total(perwt * disadvantaged_youth), by(statefip)
egen disadvantaged_puma = total(perwt * disadvantaged_youth), by(statefip puma)

gen disadvantaged_percentage = disadvantaged_puma / disadvantaged_state

egen youth_total = total(perwt * youth)
egen unemployed_total = total(perwt * unemployed)
egen disadvantaged_total = total(perwt * disadvantaged_youth)

gen youth_percentage_state = youth_state/youth_total
gen unemployed_percentage_state = unemployed_state/unemployed_total
gen disadvantaged_percentage_state = disadvantaged_state/disadvantaged_total

gen state_money = 1000 * .02 + 1000 * youth_percentage_state + 1000 * unemployed_percentage_state + 1000 * disadvantaged_percentage_state

egen npumas = nvals(puma), by(statefip)

gen puma_money = (state_money/3) * (youth_percentage + unemployed_percentage + disadvantaged_percentage)
gen numjobspuma = puma_money / .0105 //.0105 is a 10,500 dollar per yr job ($15*30hrs*12weeks in summer and $15*10hrs*34weeks in schoolyr)
//alternatively, could be doled out as 48 weeks of $15/hr pay 15 hrs a week
gen numjobsstate = state_money / .0105

*figure out households w/ youth in them
egen householdwithyouth = max(youth), by(serial)
*youth hh's living in poverty
gen youthinpov = (householdwithyouth & (poverty <= 100) & pernum == 1)
tab youthinpov if pernum == 1 [fweight = perwt]
*162 jobs for 5287 households
save "/Users/braddv/Desktop/BERNIE/employamericansnow/bernie5-1.dta", replace
keep if youthinpov
bysort statefip puma: gen runningwt = sum(hhwt)
keep serial pernum runningwt
joinby serial pernum using "/Users/braddv/Desktop/BERNIE/employamericansnow/bernie5-1.dta", unmatched(both)
gen jobsleft = 0
gen prevwt = 0
replace prevwt = runningwt - hhwt if runningwt > numjobspuma
replace jobsleft = numjobspuma - prevwt if (prevwt < numjobspuma & prevwt > 0)
gen newhhwt = hhwt
expand 2 if jobsleft > 0, generate(duplicate)
replace newhhwt = jobsleft if duplicate == 1
replace newhhwt = hhwt-jobsleft if duplicate == 0

gen job_money = 0
replace job_money = 10500 if (youthinpov & pernum == 1) & ((jobsleft > 0 & duplicate == 1) | duplicate == 0)

gen familyincome = inctot
replace familyincome = ftotinc if ftotinc < 9999999
replace familyincome = 0 if familyincome < 0

gen newincome = familyincome+job_money

gen povline = 11670 + (numprec-1)*4060
gen outofpov = disadvantaged & (newincome > povline) & (newincome < 9999999)

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

sgini newincome if pernum == 1 & familyincome < 9999999 [fweight=hhwt]
sgini familyincome if pernum == 1 & familyincome < 9999999 [fweight=hhwt]

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

egen totalhh = sum(hhwt) if pernum == 1
egen p0 = sum(hhwt) if poverty < 100 & pernum == 1

egen p1 = sum((povgap*hhwt)/povline)
disp p1/totalhh
//.22842
egen newp1 = sum((newpovgap*hhwt)/povline)
disp newp1/totalhh
//.19363

egen p2 = sum((povgap/povline)^2*hhwt)
egen newp2 = sum((newpovgap/povline)^2*hhwt)

disp p2/totalhh
//.1659
disp newp2/totalhh
//.1356

disp p0[23]/totalhh
//.19710145

egen newp0 = sum(hhwt) if ((poverty < 100 & pernum == 1) & !(outofpov == 1 & pernum == 1))
disp newp0[23]/totalhh
//.1978997

egen totalhhstate = sum(hhwt) if pernum == 1, by(statefip)
egen p0state = sum(hhwt) if poverty < 100 & pernum == 1, by(statefip)
egen newp0state = sum(hhwt) if ((poverty < 100 & pernum == 1) & !(outofpov == 1 & pernum == 1)), by(statefip)

/*. keep if youthinpov
(2,915,463 observations deleted)

. bysort statefip puma: gen runningwt = sum(hhwt)

. keep serial pernum runningwt

. joinby serial pernum using "/Users/braddv/Desktop/BERNIE/employamericansnow/bernie4-11.dta", unmatched(both)
*/

/* collapse (mean) state_money, by(statefip)
. export delimited using "/Users/braddv/Desktop/BERNIE/state_money.csv",
how to collapse without losing data? or i guess just use file again.
*/
//tab occ2010 if statefip==06 & youth [fweight=perwt] (california young jobs distribution)
//
/*collapse (mean) youth_state, by(statefip)
export delimited using "/Users/braddv/Desktop/BERNIE/youth_state.csv"*/
/*collapse (mean) disadvantaged_state, by(statefip)
export delimited using "/Users/braddv/Desktop/BERNIE/disadvantaged_state.csv"*/
/*collapse (mean) unemployed_state, by(statefip)
export delimited using "/Users/braddv/Desktop/BERNIE/unemployed_state.csv"*/
/*collapse (mean) unemployed_youth_state, by(statefip)
export delimited using "/Users/braddv/Desktop/BERNIE/unemployed_youth_state.csv"*/
/*collapse (mean) numjobsstate, by(statefip)
export delimited using "/Users/braddv/Desktop/BERNIE/numjobs_state.csv"*/

//tab job_money if pernum == 1 [fweight = hhwt]


Fix bug in CC.do.

Fix bug in CC.do.

redo-ifchange config.sh
. ./config.sh

exec >$3
cat <<-EOF
	redo-ifchange \$SRCDIR/\$2.c
	temp=\$($CC $CFLAGS -MD -MF /dev/fd/1 -o \$3 -c \$SRCDIR/\$2.c)
	echo \$temp | sed 's/^[^:]*://g' | sed 's/ \\\\//g' | xargs redo-ifchange
EOF
chmod +x $3

redo-ifchange config.sh
. ./config.sh

exec >$3
cat <<-EOF
	redo-ifchange \$SRCDIR/\$2.c
	temp=\$($CC $CFLAGS -MD -MF /dev/fd/1 -o \$3 -c \$SRCDIR/\$2.c)
	echo $temp | sed 's/^[^:]*://g' | sed 's/ \\\\$//g' | xargs redo-ifchange
EOF
chmod +x $3


iebiolstart help : Removed reference do file

Removed all references to the command creating a new do file.

{smcl}
{* 31 Jan 2017}{...}
{hline}
help for {hi:ieboilstart}
{hline}

{title:Title}

{phang}{cmdab:ieboilstart} {hline 2} Harmonizes settings across team members in the same project to the longest extent technically possible.

{phang}{hi:DISCLAIMER} {hline 1} Due to technical reasons, it is
impossible to guarantee that different types of Stata (version number, Small/IC/SE/MP
or PC/Mac/Linux) work exactly the same in every possible context. This command does not
guarantee against any version discrepancies, it is solely a collection of common practices
to reduce the risk of the same code running differently on different computers. See more
details {help ieboilstart##comp:below}.

{marker synt}{...}
{title:Syntax}

{phang}Note that due to technical requirements in Stata, to include the most
	important setting in this command you must include the second line below.{p_end}

{pmore}
{cmdab:ieboilstart} , {cmdab:v:ersionnumber(}{it:version_number}{cmd:)}  [{it:optional_options}]{break}
`r(version)'

{phang}The second line "`r(version)'" uses the command {help version} to set the same Stata version accross all
	users. "`r(version)'" is identical to setting the version to the version number set in {cmdab:v:ersionnumber()} but
	both helps standardize this setting across different parts in the project and function as a reminder to
	set the version number. {p_end}

{marker opts}{...}
{synoptset 20}{...}
{synopthdr:options}
{synoptline}
{synopt :{cmdab:v:ersionnumber(}{it:string}{cmd:)}}sets a stable version of Stata
	for all users. This option does {ul:nothing} unless "`r(version)'" is included as in the example above.{p_end}
{synopt :{cmdab:maxvar(}{it:numlist}{cmd:)}}manually sets the maximum number of
	variables allowed in a data set. The default if omitted is 32,767.{p_end}
{synopt :{cmdab:matsize(}{it:numlist}{cmd:)}}manually sets the maximum number of
	variables allowed in an estimation command, for example {help regress:regress}.
	The default if omitted is 400.{p_end}
{synopt :{cmdab:noclear}}prevents the command to clear all data which some settings
	require. Best practice is to use this command before opening any data.{p_end}
{synopt :{cmdab:q:uietly}}suppresses the output with the disclaimer and the list
	of settings.{p_end}
{synopt :{cmdab:veryquietly}}does what {cmdab:quietly} does, but also suppresses the
	reminder to include "`r(version)'".{p_end}
{synopt :{cmdab:setmem(}{it:string}{cmd:)}}manually sets the memory for	Stata 11 users.{p_end}
{synopt :{cmdab:c:ustom(}{it:string}{cmd:)}}allows the user to enter custom lines
	of code to be added.{p_end}
{synoptline}

{marker desc}{...}
{title:Description}

{pstd}{cmdab:ieboilstart} standardizes best practice settings across all users using for a project.
	Such standardized code is usually referred to as boilerplate code, and that is
	where {cmdab:ieboilstart} lends it's name from. Standardizing the boilerplate code
	in a project reduces the risk that code behaves differently across users regardless of
	what version and type of Stata they are running.

{pstd}A command like this is impossible to make comprehensive in terms of versions control. Therefore,
	the ambition of this command is only to provide a convenient way to include boilerplate code based
	on commonly used best practices, which is much better than having no boilerplate code at all. The default
	values used are the values that are standard in boilerplate code for dofiles written or Impact
	Evaluations at DIME, World Bank. Suggestions for additions or improvements are very welcomed. See
	the {help ieboilstart##auth:author} section	for contact details.

{marker comp}{...}
{title:Compatibility Across Different Stata:}

{pstd}{cmdab:ieboilstart} sets settings that increases compatibility between Stata 11.0-14.1, Stata Small/IC/SE/MP and Stata for	PC/Mac/Linux. {it:Increase compatibility} does not mean an absolute guarantee that all code will always
	work the same in different types of Stata. That is technically impossible. {it:Increase compatibility} here means reducing the risk of code working differently in different types of Stata.

{pstd}{cmdab:ieboilstart} does sometimes apply different settings for different users as all settings does not work for all versions and types of Stata. For example, new memory settings were introduced in Stata 12 and {inp:set maxvar} is not allowed in Stata IC. {cmdab:ieboilstart} is implemented to set the settings in each version and type of Stata that reduces the risk of errors when different users run the same code, but the only way to eliminate the risk completely, is to use exactly the same version of Stata.

{pstd}In addition to version control, {cmdab:ieboilstart} allows a project to 	standardize user preference settings such as {help set varabbrev:varabbrev} that 		can cause code to behave differently across users.

{title:Important Details on Version Setting:}

{pstd}Impact Evaluations and other research projects often span over many
	years, which means that the same code is likely to run in different versions
	of Stata. Stata provides an method to reduce the risk of discrepancies due to this. See {help version:version} settings for more details. This method is included in {cmdab:ieboilstart}, however, {cmd:version} is mainly intended for making code written in Stata 11 to work
	in Stata 14 and not necessarily the other way around. Setting the version is still best practice and perhaps the most important setting in {cmdab:ieboilstart}. Read the {help ieboilstart##synt:syntax section} on the extra step required for {cmdab:ieboilstart} to set the version.{p_end}

{pstd}{hi:Warning:} Any dofiles containing randomization {ul:{hi:MUST}} set the version number
	as Stata occasionally makes updates to its randomization algorithm between versions. A dofile including random assignment
	or random sampling is therefore not necessarily stable across different versions of Stata,
	unless the dofile has a version number explicitly set in the beginning of the file.{p_end}

	{pstd}The version setting has the scope of a local, meaning that it expires when a dofile and all sub-dofiles it is calling are completed. Therefore, set the version in your master dofile {ul:and} in every single dofile using randomization. This will make your randomization stable even if another user would only run the specific dofile with the randomization.{p_end}

{title:Details on Memory Settings:}

{pstd}In Stata versions before Stata 12, memory was assigned statically from the
	computer memory, meaning that there was a fixed amount of memory assigned to Stata
	regardless if required it or not. Stata would crash if it went over that fixed limit
	when for example increasing the data set or running a complex calculation. In Stata
	12 and more recent versions, this is done dynamically, meaning that Stata is assigned
	a little bit of memory when it is starts and assigned additional memory dynamically
	as needed. The only memory limit is the hardware limits on the computer it is running
	on.

{pstd}The fixed memory in Stata 11 was assigned by the command {cmdab:set memory}. This
	command is simply ignored in Stata 12 or later. Instead the dynamic memory setting
	can be fine tuned with {cmdab:min_memory}, {cmdab:max_memory}, {cmdab:niceness} and
	{cmdab:segmentsize}, although even highly advanced users rarely have to worry about these settings as long as they are set to the recommended default values
	(which this command ensures that they are).

{p2colset 5 22 24 2}
{p2col : Memory Settings}Short explanation{p_end}
{p2line}
{pstd}{it: Basic Settings:}{p_end}
{p2col :{cmdab:set maxvar}}sets the maximum number of variables allowed. The
	default value is 32,767 the maximum allowed in Stata MP or SE. A lower maximum number can manually be set by the option {cmdab:maxvar()}. This setting is skipped using an if-statement if the dofile is executed in Stata Small or IC. See {help set maxvar:set maxvar}.{p_end}
{p2col :{cmdab:set matsize}}sets the maximum number of variables that can be included in estimation commands such as {cmd:regress}. The {cmdab:ieboilstart} default value is 400 which is the default value for Stata. The maximum number can manually be set by the option {cmdab:matsize()} as long as the number does not violate the limitations in your version of Stata. See {help set matsize:set matsize}.{p_end}
{break}
{pstd}{it: Dynamic Memory Settings (see {help memory:memory} for details and reasons for default values. Few users ever need to change these values):}{p_end}
{p2col :{cmdab:set min_memory}}sets a lower bound for the amount of memory assigned to Stata. The default value is no lower bound.{p_end}
{p2col :{cmdab:set max_memory}}sets an upper bound for the amount of memory assigned to Stata. The default is as much as the hardware of the computer allows.{p_end}
{p2col :{cmdab:set niceness}}defines how quickly Stata releases unused memory back to the computer{p_end}
{p2col :{cmdab:set segmentsize}}defines how large bundles of data is assigned each time
			Stata request more memory. Too large bundles make Stata occupy an
			unnecessary large part of the computer's memory (that otherwise could
			have been used by other applications), and too small bundles make
			Stata frequently consume processing power requesting new bundles.{p_end}
{break}
{pstd}{it: Static Memory Settings (only applicable in Stata 11)}{p_end}
{p2col :{cmdab:set memory}}sets the amount of static memory assigned to Stata. {p_end}
{p2line}

{pstd}{hi:{ul:Other Settings:}}{break}The other settings are included as they are either very
	commonly preferred or reduces the risk of errors for users that do not yet fully understand
	the implication of setting these settings to other values than what is recommended. These
	settings can be reverted to personal preferences after running {cmdab:ieboilstart} or by using the {cmd:custom()} option.{p_end}
{p2colset 5 24 26 2}
{p2col : Other Settings}Short explanation{p_end}
{p2line}
{p2col :{cmdab:set more off}}disables the default setting that Stata stops and
	waits for the user to press any key each time the output window is full. Long
	dofiles would take a very long time to run and require constant attention from
	the user without this setting. Most Stata users always disable the default
	which is {cmdab:set more on}. See {help set more:set more}.{p_end}
{p2col :{cmdab:pause on}}allows the usage of the command {cmdab:pause} which can
	be very useful during debugging. See {help pause:pause}.{p_end}
{p2col :{cmdab:set varabbrev off}}allows users to abbreviate variable names
		similarly to command names such as gen for generate and reg for regress.
		However, while command abbreviation has strict rules constant across data sets, users, and
		Stata versions; variable name abbreviation does not have the same strict rules
		and consistency. While enabling variable abbreviation can speed up coding,
		it is an error-prone technique unless all users using a dofile with
		variable abbreviations organize their coding practices exactly the same
		way. See {help set varabbrev:set varabbrev} for more details and carfully
		consider this caution before enabling variable abbreviations in a
		collaborative dofile.{p_end}
{p2line}

{title:Options}

{phang}{cmdab:v:ersionnumber(}{it:string}{cmd:)} sets a stable version of Stata
	for all users. Stata does not (for good reasons) allow a user written command
	to alter the version setting from inside a command. Therefore, this option does
	{ul:nothing} unless "`r(version)'" is included as described in the
	{help ieboilstart##synt:syntax section}. While the version number cannot be set
	inside the command code, {cmd:ieboilstart} does two things. First it reminds
	the user to set the version since it is a required command. Second, it makes
	sure that the version number used is not too old. A too old version might
	risk that there are far too big a difference in many commands. Best
	practice is therefore to keep the same version number throughout a project,
	unless there is something specific to a newer version that is required for any
	dofile. Only major and recent	versions are allowed in order to reduce errors and
	complexity. The valid versions	are 11.0, 11.1, 11.2, 12.0, 12.1, 13.0, 13.1,
	14.0 and 14.1. All versions of Stata can be set to run any older version of Stata
	but not a newer. It is recommended to use a .1 over a .0 version. .1 is free
	of charge	if you already have the corresponding .0 and .1 includes bug fixes to the
	functions introduced in .0.{p_end}

{phang}{cmdab:maxvar(}{it:numlist}{cmd:)} manually sets the maximum number of
	variables allowed in a data set. The default is to set the number to the highest
	allowed. Reducing this number can occasionally improve performance, but modern
	computers running Impact Evaluations analysis are more likely to
	face the problem of too few variables allowed than running out of
	memory. The maximum number allowed is 2047 in Stata IC and 32,767 in Stata MP
	or SE. This setting is ignored for users that use Stata IC or Stata Small.{p_end}

{phang}{cmdab:matsize(}{it:numlist}{cmd:)} manually sets the maximum number of
	variables allowed in estimation commands, for example {help reg:regress}.
	The default is to set the number to the highest allowed in your version of Stata.
	Reducing this number can occasionally improve performance, but modern
	computers running Impact Evaluations analysis are more likely
	to run into problems allowing too few variables than running out of memory.
	Although, this is more likely the case with {cmdab:maxvar} than
	with {cmdab:matsize}. The maximum number allowed is 800 in Stata IC and 11,000 in Stata
	MP or SE.{p_end}

{phang}{cmdab:noclear} prevents the command from clearing/deleting the data set
	in working memory. No data may be in working memory in order to modify
	settings for maxvar, min_memory, max_memory and segmentsize. That is why the default
	is to clear the data set stored in working memory. Working memory is your RAM
	memory so no data saved to your hard drive will ever be deleted by this command.
	This command is intended to be placed at the very top of a dofile, so the
	data needed could be loaded into memory after running {cmd:ieboilstart}. For the
	reasons above, {cmdab:noclear} and {cmdab:maxvar()} cannot be combined.{p_end}

{phang}{cmdab:q:uietly} suppresses two of three outputs this commands generates in the result window. The first output is a disclaimer warning the user that there is no guarantee that commands will always behave identically. The second output is a list of all the settings applied and their values..{p_end}

{phang}{cmd:veryquietly} suppresses the third output this commands generates in the result window in addition to the two that {cmd:quietly} is suppressing. The third output is a reminder to set the version number using "`r(version)'" after running the command.

{phang}{cmdab:c:ustom(}{it:string}{cmd:)} allows the user to add one or multiple custom lines of code. Each line of code should be seperated with a "@". See example 4
	below for more details.{p_end}

{phang}{cmdab:c:ustom(}{it:string}{cmd:)}This option is only relevant for users of Stata 11. This value must be an integer followed by the letter B, K, M or G. The default if omitted is 50M. Cannot be used if
	versionnumber() is set to version 12.0 or more recent. See {help set memory} for more details. This link will only display options relevant to Stata 11 when clicking it in Stata 11. Otherwise it will show the options relevant to Stata 12 and later.

{title:Examples}

{pstd}{hi:Example 1.}

{pmore}{inp:ieboilstart, versionnumber(11.1)}
{break}`r(version)'

{pmore}After running the two lines of code above all users will run their version
 of Stata as if the version was  11.1. That means that anyone who bought or
 upgraded Stata after June 2010 can use the command and all commands will behave
  identically for all those users. All other settings have been set to common
	best practice values.

{pstd}{hi:Example 2.}

{pmore}{inp:ieboilstart, versionnumber(12.1) custom(ssc install estout @ ssc install winsor)}
{break}`r(version)'

{pmore}In the example above, the version is set to 12.1. When running this command, it also makes sure that the user has the two commands {inp:estout} and {inp:winsor} installed.

{title:Acknowledgements}

{phang}I would like to acknowledge the help in testing and proofreading and suggestions I
	received in relation to this command and help file from (in alphabetic order):{p_end}
{pmore}Michell Dong{break}John Dundas{break}Paula Gonzales{break}Seungmin Lee{break}Srujith Lingala{break}William Lisowski{break}Daniel Klein

{marker auth}{...}
{title:Author}

{phang}Kristoffer Bjarkefur, The World Bank, DECIE

{phang}Please send bug-reports, suggestions and requests for clarifications
		 writing "ietools ieboilstart" 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}
{* 26 Dec 2016}{...}
{hline}
help for {hi:ieboilstart}
{hline}

{title:Title}

{phang}{cmdab:ieboilstart} {hline 2} Creates a dofile that harmonizes the settings
accross team members in the same project to the longest extent technically possible.

{phang}{hi:DISCLAIMER} {hline 1} Due to technical reasons why it is
impossible to guarantee that different types of Stata (version number, Small/IC/SE/MP
or PC/Mac/Linux) work exactly the same in every possible context. This command does not
guarantee against any version discrepancies, it is solely a collection of common practices
to reduce the risk of the same code running differently on different computers. See more
details {help ieboilstart##comp:below}.

{marker synt}{...}
{title:Syntax}

{phang}Note that due to technical requirements in Stata, to include the most
	important setting in this command you must include the second line below.{p_end}

{pmore}
{cmdab:ieboilstart} , {cmdab:v:ersionnumber(}{it:version_number}{cmd:)}  [{it:optional_options}]{break}
`r(version)'

{phang}The second line "`r(version)'" uses the command {help version} to set the same Stata version accross all
	users. "`r(version)'" is identical to setting the version to the version number set in {cmdab:v:ersionnumber()} but
	both helps standardize this setting across different parts in the project and function as a reminder to
	set the version number. {p_end}

{marker opts}{...}
{synoptset 20}{...}
{synopthdr:options}
{synoptline}
{synopt :{cmdab:v:ersionnumber(}{it:string}{cmd:)}}sets a stable version of Stata
	for all users. This option does {ul:nothing} unless "`r(version)'" is included as in the example above.{p_end}
{synopt :{cmdab:maxvar(}{it:numlist}{cmd:)}}manually sets the maximum number of
	variables allowed in a data set. The default if omitted is 32,767.{p_end}
{synopt :{cmdab:matsize(}{it:numlist}{cmd:)}}manually sets the maximum number of
	variables allowed in an estimation command, for example {help regress:regress}.
	The default if omitted is 400.{p_end}
{synopt :{cmdab:noclear}}prevents the command to clear all data which some settings
	require. Best practice is to use this command before opening any data.{p_end}
{synopt :{cmdab:q:uietly}}suppresses the output with the disclaimer and the list
	of settings.{p_end}
{synopt :{cmdab:veryquietly}}does what {cmdab:quietly} does, but also suppresses the
	reminder to include "`r(version)'".{p_end}
{synopt :{cmdab:setmem(}{it:string}{cmd:)}}manually sets the memory for	Stata 11 users.{p_end}
{synopt :{cmdab:c:ustom(}{it:string}{cmd:)}}allows the user to enter custom lines
	of code to be added to the dofile this command creates.{p_end}
{synoptline}

{marker desc}{...}
{title:Description}

{pstd}{cmdab:ieboilstart} standardizes best practice settings across all users using for a project.
	Such standardized code is usually referred to as boilerplate code, and that is
	where {cmdab:ieboilstart} lends it's name from. Standardizing the boilerplate code
	in a project reduces the risk that code behaves differently across users regardless of
	what version and type of Stata they are running.

{pstd}A command like this is impossible to make comprehensive in terms of versions control. Therefore,
	the ambition of this command is only to provide a convenient way to include boilerplate code based
	on commonly used best practices, which is much better than having no boilerplate code at all. The default
	values used are the values that are standard in boilerplate code for dofiles written or Impact
	Evaluations at DIME, World Bank. Suggestions for additions or improvements are very welcomed. See
	the {help ieboilstart##auth:author} section	for contact details.

{marker comp}{...}
{title:Compatibility Across Different Stata:}

{pstd}{cmdab:ieboilstart} sets settings that increases compatibility between Stata 11.0-14.1, Stata Small/IC/SE/MP and Stata for	PC/Mac/Linux. {it:Increase compatibility} does not mean an absolute guarantee that all code will always
	work the same in different types of Stata. That is technically impossible. {it:Increase compatibility} here means reducing the risk of code working differently in different types of Stata.

{pstd}{cmdab:ieboilstart} does sometimes apply different settings for different users as all settings does not work for all versions and types of Stata. For example, new memory settings were introduced in Stata 12 and {inp:set maxvar} is not allowed in Stata IC. {cmdab:ieboilstart} is implemented to set the settings in each version and type of Stata that reduces the risk of errors when different users run the same code, but the only way to eliminate the risk completely, is to use exactly the same version of Stata.

{pstd}In addition to version control, {cmdab:ieboilstart} allows a project to 	standardize user preference settings such as {help set varabbrev:varabbrev} that 		can cause code to behave differently across users.

{title:Important Details on Version Setting:}

{pstd}Impact Evaluations and other research projects often span over many
	years, which means that the same code is likely to run in different versions
	of Stata. Stata provides an method to reduce the risk of discrepancies due to this. See {help version:version} settings for more details. This method is included in {cmdab:ieboilstart}, however, {cmd:version} is mainly intended for making code written in Stata 11 to work
	in Stata 14 and not necessarily the other way around. Setting the version is still best practice and perhaps the most important setting in {cmdab:ieboilstart}. Read the {help ieboilstart##synt:syntax section} on the extra step required for {cmdab:ieboilstart} to set the version.{p_end}

{pstd}{hi:Warning:} Any dofiles containing randomization {ul:{hi:MUST}} set the version number
	as Stata occasionally makes updates to it's randomization algorithm between versions. A dofile including random assignment
	or random sampling is therefore not necessarily stable across different versions of Stata,
	unless the dofile has a version number explicitly set in the beginning of the file.{p_end}

	{pstd}The version setting has the scope of a local, meaning that it expires when a dofile and all sub-dofiles it is calling are completed. Therefore, set the version in your master dofile {ul:and} in every single dofile using randomization. This will make your randomization stable even if another user would only run the specific dofile with the randomization.{p_end}

{title:Details on Memory Settings:}

{pstd}In Stata versions before Stata 12, memory was assigned statically from the
	computer memory, meaning that there was a fixed amount of memory assigned to Stata
	regardless if required it or not. Stata would crash if it went over that fixed limit
	when for example increasing the data set or running a complex calculation. In Stata
	12 and more recent versions, this is done dynamically, meaning that Stata is assigned
	a little bit of memory when it is started and assigned additional memory dynamically
	as needed. The only memory limit is the hardware limits on the computer it is running
	on.

{pstd}The fixed memory in Stata 11 was assigned by the command {cmdab:set memory}. This
	command is simply ignored in Stata 12 or later. Instead the dynamic memory setting
	can be fine tuned with {cmdab:min_memory}, {cmdab:max_memory}, {cmdab:niceness} and
	{cmdab:segmentsize}, although even highly advanced users rarely have to worry about these settings as long as they are set to the recommended default values
	(which this command ensures that they are).

{p2colset 5 22 24 2}
{p2col : Memory Settings}Short explanation{p_end}
{p2line}
{pstd}{it: Basic Settings:}{p_end}
{p2col :{cmdab:set maxvar}}sets the maximum number of variables allowed. The
	default value is 32,767 the maximum allowed in Stata MP or SE. A lower maximum number can manually be set by the option {cmdab:maxvar()}. This setting is skipped using an if-statement if the dofile is executed in Stata Small or IC. See {help set maxvar:set maxvar}.{p_end}
{p2col :{cmdab:set matsize}}sets the maximum number of variables that can be included in estimation commands such as {cmd:regress}. The {cmdab:ieboilstart} default value is 400 which is the default value for Stata. The maximum number can manually be set by the option {cmdab:matsize()} as long as the number does not violate the limitations in your version of Stata. See {help set matsize:set matsize}.{p_end}
{break}
{pstd}{it: Dynamic Memory Settings (see {help memory:memory} for details and reasons for default values. Few users ever need to change these values):}{p_end}
{p2col :{cmdab:set min_memory}}sets a lower bound for the amount of memory assigned to Stata. The default value is no lower bound.{p_end}
{p2col :{cmdab:set max_memory}}sets an upper bound for the amount of memory assigned to Stata. The default is as much as the hardware of the computer allows.{p_end}
{p2col :{cmdab:set niceness}}defines how quickly Stata releases unused memory back to the computer{p_end}
{p2col :{cmdab:set segmentsize}}defines how large bundles of data is assigned each time
			Stata request more memory. Too large bundles make Stata occupy an
			unnecessary large part of the computer's memory (that otherwise could
			have been used by other applications), and too small bundles make
			Stata frequently consume processing power requesting new bundles.{p_end}
{break}
{pstd}{it: Static Memory Settings (only applicable in Stata 11)}{p_end}
{p2col :{cmdab:set memory}}sets the amount of static memory assigned to Stata. {p_end}
{p2line}

{pstd}{hi:{ul:Other Settings:}}{break}The other settings are included as they are either very
	commonly preferred or reduces the risk of errors for users that do not yet fully understand
	the implication of setting these settings to other values than what is recommended. These
	settings can be reverted to personal preferences after running the dofile created
	by {cmdab:ieboilstart} or by using the {cmd:custom()} option.{p_end}
{p2colset 5 24 26 2}
{p2col : Other Settings}Short explanation{p_end}
{p2line}
{p2col :{cmdab:set more off}}disables the default setting that Stata stops and
	waits for the user to press any key each time the output window is full. Long
	dofiles would take a very long time to run and require constant attention from
	the user without this setting. Most Stata users always disable the default
	which is {cmdab:set more on}. See {help set more:set more}.{p_end}
{p2col :{cmdab:pause on}}allows the usage of the command {cmdab:pause} which can
	be very useful during debugging. See {help pause:pause}.{p_end}
{p2col :{cmdab:set varabbrev off}}allows users to abbreviate variable names
		similarly to command names such as gen for generate and reg for regress.
		However, while command abbreviation has strict rules constant across data sets, users, and
		Stata versions; variable name abbreviation does not have the same strict rules
		and consistency. While enabling variable abbreviation can speed up coding,
		it is an error-prone technique unless all users using a dofile with
		variable abbreviations organize their coding practices exactly the same
		way. See {help set varabbrev:set varabbrev} for more details and carfully
		consider this caution before enabling variable abbreviations in a
		collaborative dofile.{p_end}
{p2line}

{title:Options}

{phang}{cmdab:v:ersionnumber(}{it:string}{cmd:)} sets a stable version of Stata
	for all users. Stata does not (for good reasons) allow a user written command
	to alter the version setting form insida a command. Therefore, this option does
	{ul:nothing} unless "`r(version)'" is included as described in the
	{help ieboilstart##synt:syntax section}. While the version number cannot be set
	inside the command code, {cmd:ieboilstart} does two things. First it reminds
	the user to set the version since it is a required command. Second, it makes
	sure that the version number used is not too old. A too old version might
	risk that there are far to big differences in too many commands. Best
	practice is therefore to keep the same version number throughout a project,
	unless there is something specific to a newer version that is required for any
	dofile. Only major and recent	versions are allowed in order to reduce errors and
	complexity. The valid versions	are 11.0, 11.1, 11.2, 12.0, 12.1, 13.0, 13.1,
	14.0 and 14.1. All versions of Stata can be set to run any older version of Stata
	but not a	newer. It is recommended to use a .1 over a .0 version. .1 is free
	of charge	if you already have the corresponding .0 and .1 includes bug fixes to the
	functions introduced in .0.{p_end}

{phang}{cmdab:maxvar(}{it:numlist}{cmd:)} manually sets the maximum number of
	variables allowed in a data set. The default is to set the number to the highest
	allowed. Reducing this number can occasionally improve performance, but modern
	computers running Impact Evaluations analysis are more likely to
	face the problem of too few variables allowed than running out of
	memory. The maximum number allowed is 2047 in Stata IC and 32,767 in Stata MP
	or SE. This setting is ignored for users that use Stata IC or Stata Small.{p_end}

{phang}{cmdab:matsize(}{it:numlist}{cmd:)} manually sets the maximum number of
	variables allowed in estimation commands, for example {help reg:regress}.
	The default is to set the number to the highest allowed in your version of Stata.
	Reducing this number can occasionally improve performance, but modern
	computers running Impact Evaluations analysis are more likely
	to run into problems allowing too few variables than running out of memory.
	Although, this is more likely the case with {cmdab:maxvar} than
	with {cmdab:matsize}. The maximum number allowed is 800 in Stata IC and 11,000 in Stata
	MP or SE.{p_end}

{phang}{cmdab:noclear} prevents the command from clearing/deleting the data set
	in working memory. No data may be in working memory in order to modify
	settings for maxvar, min_memory, max_memory and segmentsize. That is why the default
	is to clear the data set stored in working memory. Working memory is your RAM
	memory so no data saved to your hard drive will ever be deleted by this command.
	This command is intended to be placed at the very top of a dofile, so the
	data needed could be loaded into memory after running {cmd:ieboilstart}. For the
	reasons above, {cmdab:noclear} and {cmdab:maxvar()} cannot be combined.{p_end}

{phang}{cmdab:q:uietly} suppresses two of three outputs this commands generates in the result window. The first output is a disclaimer warning the user that there is no guarantee that commands will always behave identically. The second output is a list of all the settings applied and their values..{p_end}

{phang}{cmd:veryquietly} suppresses the third output this commands generates in the result window in addition to the two that {cmd:quietly} is suppressing. The third output is a reminder to set the version number using "`r(version)'" after running the command.

{phang}{cmdab:c:ustom(}{it:string}{cmd:)} allows the user to add one or multiple custom lines of code
	to the do-file. Each line of code should be seperated with a "@". See example 4
	below for more details.{p_end}

{phang}{cmdab:c:ustom(}{it:string}{cmd:)}This option is only relevant for users of Stata 11. This value must be an integer followed by the letter B, K, M or G. The default if omitted is 50M. Cannot be used if
	versionnumber() is set to version 12.0 or more recent. See {help set memory} for more details. This link will only display options relevant to Stata 11 when clicking it in Stata 11. Otherwise it will show the options relevant to Stata 12 and later.

{title:Examples}

{pstd}{hi:Example 1.}

{pmore}{inp:ieboilstart, versionnumber(11.1)}
{break}`r(version)'

{pmore}After running the two lines of code above all users will run their version
 of Stata as if the version was  11.1. That means that anyone who bought or
 upgraded Stata after June 2010 can use this dofile and all commands will behave
  identically for all those users. All other settings have been set to common
	best practice values.

{pstd}{hi:Example 2.}

{pmore}{inp:ieboilstart, versionnumber(12.1) custom(ssc install estout @ ssc install winsor)}
{break}`r(version)'

{pmore}In the example above, the version is set to 12.1. When running this command it also makes sure that the user has the two commands {inp:estout} and {inp:winsor} installed.

{title:Acknowledgements}

{phang}I would like to acknowledge the help in testing and proofreading and suggestions I
	received in relation to this command and help file from (in alphabetic order):{p_end}
{pmore}Michell Dong{break}John Dundas{break}Paula Gonzales{break}Seungmin Lee{break}Srujith Lingala{break}William Lisowski{break}Daniel Klein

{marker auth}{...}
{title:Author}

{phang}Kristoffer Bjarkefur, The World Bank, DECIE

{phang}Please send bug-reports, suggestions and requests for clarifications
		 writing "ietools ieboilstart" 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"}


Update bettertab.ado

Update bettertab.ado

forgot to add if/in qualifier

*! V0.1 31012017, Apoorva Lal
// wrapper for tab / tab2 that adds value prefixes for factor variables
cap pr drop bettertab
pr def bettertab
	version 6
	syntax varlist [if] [in]
	marksample touse
	loc nvars : list sizeof varlist
	if `nvars' == 1 {
		loc tabcmd tab
	}
	else {
		loc tabcmd tab2
	}
	loc label_list ""
	foreach v in `varlist' {
		cap conf var `v'
		if !_rc {
			loc la_`v': value label `v'
			loc label_list `label_list' `la_`v''
		}
		else {
			noi di "`v' not found"
			error
		}
	}
	numlabel `label_list', add
	`tabcmd' `varlist' if `touse'
	numlabel `label_list', remove
end

*! V0.1 31012017, Apoorva Lal
// wrapper for tab / tab2 that adds value prefixes for factor variables
cap pr drop bettertab
pr def bettertab
	version 6
	syntax varlist [if] [in]
	marksample touse
	loc nvars : list sizeof varlist
	if `nvars' == 1 {
		loc tabcmd tab
	}
	else {
		loc tabcmd tab2
	}
	loc label_list ""
	foreach v in `varlist' {
		cap conf var `v'
		if !_rc {
			loc la_`v': value label `v'
			loc label_list `label_list' `la_`v''
		}
		else {
			noi di "`v' not found"
			error
		}
	}
	numlabel `label_list', add
	`tabcmd' `varlist'
	numlabel `label_list', remove
end


Minor spelling fixes

Minor spelling fixes

{smcl}
{* 26 Dec 2016}{...}
{hline}
help for {hi:iegraph}
{hline}

{title:Title}

{phang2}{cmdab:iegraph} {hline 2} Generates graphs based on regressions with treatment dummies common in impact evaluations.

{title:Syntax}

{phang2}
{cmdab:iegraph} {varlist}
, [{cmd:noconfbars} {cmdab:ti:tle(}{it:string}{cmd:)}
{cmdab:save(}{it:string}{cmd:)} {cmdab:confbarsnone(}{it:varlist}{cmd:)}
{it:any towway graph options}
]

{marker opts}{...}
{synoptset 22}{...}
{synopthdr:options}
{synoptline}
{synopt :{cmd:noconfbars}} Removes the confidence interval bars from graphs for all treatments.{p_end}
{synopt :{cmdab:ti:tle(}{it:string}{cmd:)}} Manually sets the title of the graph.{p_end}
{synopt :{cmdab:save(}{it:string}{cmd:)}} Sets the filename and the directory to which the graph will be set/exported.{p_end}
{synopt :{cmdab:confbarsnone(}{it:varlist}{cmd:)}} Removes confidence interval bars from only the {it:varlist} listed.{p_end}
{synopt :{cmdab:yzero}} Forces y-axis on the graph to start at 0.{p_end}
{synopt :{cmdab: Graph Options}} Options that can be used with normal graph commands can also be used. See example 2 for details.{p_end}
{synoptline}

{marker desc}
{title:Description}

{pstd}{cmdab:iegraph} This command creates bar graphs on the based on the coefficients
	of treatment dummies in regression results. This command is developed for reading
	stored results of from two types of impact evaluation regression models, but there
	are countless of other examples where the command also can be used. {cmd:iegraph} must
	be used immediately after running the regression or as long as the regression result is
	still stored in or restored to Stata's {help ereturn} results.

{pstd}{bf:Model 1: OLS with Treatment Dummies}{break}The most typical impact evaluation regression is
	to have the outcome variable as the dependent variable and one dummy for each
	treatment arm where control is the omitted category. These regressions can also include
	covariates, fixed effects etc., but as long as the treatment status is defined by
	mutually exclusive dummy variables. See especially example 1 and 2 below. This command
	works with any number of treatment arms but works best from two arms (treatment
	and control) to five treatment arms (4 different treatments and control). More
	arms than that may result in a still correct but perhaps cluttered graph.

{pstd}{bf:Model 2: Difference-in-Differences}{break}Another typical regression model in impact
	evaluations are difference-in-difference (Diff-in-Diff) models with two treatment arms (treatment
	and control) and two time periods. If the Diff-in-Diff regression is specified as having the
	outcome variable as the dependent variable and three dummy variables (time, treatment
	and timeXtreatment) as the independent variables, then this command will produce a nice
	graph. Controls, treatment effects etc. may be added to the regression model. See especially example 3.

{pstd}{bf:Graph Output}{break}The graph generated by this command is created using the following values. The
	control bar is the mean of the outcome variable for the control group. It is not
	the constant from the regression as those are not identical if, for example, fixed effects
	and covariates were used. For each treatment group the bar is the sum of the value
	of the control bar and the beta coefficient in the regression of the corresponding
	treatment dummy. The confidence intervals are calculated from the variance in the
	beta coefficients in the regression.{p_end}

{pstd}The graph also includes the N for each treatment arm in the regression and uses
	that value as labels on the x-axis. Stars are added to this value if the corresponding
	coefficient is statistically different from zero in the regression{p_end}

{marker optslong}
{title:Options}

{phang}{cmd:noconfbars} Removes the confidence interval bars from graphs for all
	treatments. The default value for the confidence interval bars ar 95%. {p_end}

{phang}{cmdab:ti:tle(}{it:string}{cmd:)} Manually sets the title of the graph.{p_end}

{phang}{cmdab:save(}{it:string}{cmd:)} Sets the filename and the directory to which
	the graph will be set. If the filename ends with no extension or '.gph', it will be
	saved in the graph format. Extensions(png,pdf,tif,wmf,emf,ps,and eps) will be exported.
	Wmf and Emf are only available for the Windows version of Stata. Png and Tif for all
	versions of Stata except Console.{p_end}

{phang}{cmdab:confbarsnone(}{it:varlist}{cmd:)} Removes confidence interval bars
	from only the {it:varlist} listed. The remaining variables in the graphs which
	have not been specified in {cmdab:confbarsnone} will still have the confidence
	interval bars. {p_end}

{phang}{cmdab:yzero} Manually sets the y-axis of the graph to start at zero instead of the Stata default.{p_end}

{marker optslong}
{title:Examples}

{pstd} {hi:Example 1.}

{pmore} {inp:regress} {it:outcomevar treatment_dummy}{break}
		{inp:iegraph} {it:treatment_dummy} , {inp:title({it:"Treatment Effect on Outcome"})}

{pmore}In the example above, there is only two treatment arms (treatment and
		control). {it:treatment_dummy} has a 1 for all treatment observations and
		a 0 for all control observations. The graph will have one bar for control and
		it shows the mean for {it:outcomevar} for all observations in control. The
		second bar in the graph will be the sum of that mean and the coefficient
		for {it:treatment_dummy} in the regression. The graph will also have the
		title: Treatment Effect on Outcome.

{pstd} {hi:Example 2.}

{pmore} {inp:regress} {it:income tmt_1 tmt_2 age education}{inp:, cluster(}{it:district}{inp:)}{break}
		{inp:iegraph} {it:tmt_1 tmt_2}{inp:, noconfbars yzero title({it:"Treatment effect on income"}) }

{pmore}In the example above, the treatment effect on income in researched. There
		are three treatment arms; control, treatment 1 ({it:tmt_1}) and treatment
		2 ({it:tmt_2}). It is important that no observation has the value 1 in
		both {it:tmt_1} and {it:tmt_2} (i.e. no observation is in more than one
		treatment) and some observations must have the value 0 in both {it:tmt_1}
		and {it:tmt_2} (i.e. control observations). The variables {it:age} and
		{it:education} are covariates (control variables) and are not included
		in {cmd:iegraph}. {inp:noconfbars} omits the confidence interval bars
		, and {inp:yzero} sets the y-axis to start at 0.

{pstd} {hi:Example 3.}

{pmore} {inp:regress} {it:chld_wght time treat timeXtreat}{break}
		{inp:iegraph} {it:time treat timeXtreat} {inp:, title({it:"Treatment effect on Child Weight (Diff-in-Diff)"})}

{pmore}In the example above, the data set is a panel data set with two time
		periods and the regression estimates the treatment effect on child weight
		using a Difference-in-Differences model.
		The dummy variable {it:time} indicates if it is time period 0 or 1.
		The dummy variable {it:treat} indicates if the observation is treatment
		or control. {it:timeXtreat} is the interaction term of {it:time}
		and {it:treat}. This the standard way to set up a Difference-in-Differences
		regression model.

{pstd} {hi:Example 4.}

{pmore} {inp:regress} {it:harvest T1 T2 T3 } {break}
		{inp:iegraph} {it:T1 T2 T3} {inp:, title({it:"Treatment effect on harvest"})
		xlabel(,angle(45)) yzero ylabel(minmax) save({it:"$Output/Graph1.gph"})}

{pmore}The example above shows how to save a graph to disk. It also shows that
	most two-way graph options can be used. In this example the {cmd:iegraph}
	option {cdm:yzero} conflicts with the two-way option {cmd:ylabel(minmax)}.
	In such a case the user specified option takes precedence over {cmd:iegraph}
	options like {cdm:yzero}.

{title:Acknowledgements}

{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}Luiza Cardoso De Andrade{break}Michael Orevba{break}Ahmad Zia Wahdat{break}

{title:Authors}

{phang}Kristoffer Bjarkefur & Mrijan Rimal, The World Bank, DECIE

{phang}Please send bug-reports, suggestions and requests for clarifications
		 writing "ietoolkit iegraph" 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}
{* 26 Dec 2016}{...}
{hline}
help for {hi:iegraph}
{hline}

{title:Title}

{phang2}{cmdab:iegraph} {hline 2} Generates graphs based on regressions with treatment dummies common in impact evaluations.

{title:Syntax}

{phang2}
{cmdab:iegraph} {varlist}
, [{cmd:noconfbars} {cmdab:ti:tle(}{it:string}{cmd:)}
{cmdab:save(}{it:string}{cmd:)} {cmdab:confbarsnone(}{it:varlist}{cmd:)}
{it:any towway graph options}
]

{marker opts}{...}
{synoptset 22}{...}
{synopthdr:options}
{synoptline}
{synopt :{cmd:noconfbars}} Removes the confidence interval bars from graphs for all treatments.{p_end}
{synopt :{cmdab:ti:tle(}{it:string}{cmd:)}} Manually sets the title of the graph.{p_end}
{synopt :{cmdab:save(}{it:string}{cmd:)}} Sets the filename and the directory to which the graph will be set/exported.{p_end}
{synopt :{cmdab:confbarsnone(}{it:varlist}{cmd:)}} Removes confidence interval bars from only the {it:varlist} listed.{p_end}
{synopt :{cmdab:yzero}} Forces y-axis on the graph to start at 0.{p_end}
{synopt :{cmdab: Graph Options}} Options that can be used with normal graph commands can also be used. See example 2 for details.{p_end}
{synoptline}

{marker desc}
{title:Description}

{pstd}{cmdab:iegraph} This command creates bar graphs on the based on the coefficients
	of treatment dummies in regression results. This command is developed for reading
	stored results of from two types of impact evaluation regression models, but there
	are countless of other examples where the command also can be used. {cmd:iegraph} must
	be used immediately after running the regression or as long as the regression result is
	still stored in or restored to Stata's {help ereturn} results.

{pstd}{bf:Model 1: OLS with Treatment Dummies}{break}The most typical impact evaluation regression is
	to have the outcome variable as the dependent variable and one dummy for each
	treatment arm where control is the omitted category. These regressions can also include
	covariates, fixed effects etc., but as long as the treatment status is defined by
	mutually exclusive dummy variables. See especially example 1 and 2 below. This command
	works with any number of treatment arms but works best from two arms (treatment
	and control) to five treatment arms (4 different treatments and control). More
	arms than that may result in a still correct but perhaps cluttered graph.

{pstd}{bf:Model 2: Difference-in-Differences}{break}Another typical regression model in impact
	evaluations are difference-in-difference (Diff-in-Diff) models with two treatment arms (treatment
	and control) and two time periods. If the Diff-in-Diff regression is specified as having the
	outcome variable as the dependent variable and three dummy variables (time, treatment
	and timeXtreatment) as the independent variables, then this command will produce a nice
	graph. Controls, treatment effects etc. may be added to the regression model. See especially example 3.

{pstd}{bf:Graph Output}{break}The graph generated by this command is created using the following values. The
	control bar is the mean of the outcome variable for the control group. It is not
	the constant from the regression as those are not identical if, for example, fixed effects
	and covariates were used. For each treatment group the bar is the sum of the value
	of the control bar and the beta coefficient in the regression of the corresponding
	treatment dummy. The confidence intervals are calculated from the variance in the
	beta coefficients in the regression.{p_end}

{pstd}The graph also includes the N for each treatment arm in the regression and uses
	that value as labels on the x-axis. Stars are added to this value if the corresponding
	coefficient is statistically different from zero in the regression{p_end}

{marker optslong}
{title:Options}

{phang}{cmd:noconfbars} Removes the confidence interval bars from graphs for all
	treatments. The default value for the confidence interval bars ar 95%. {p_end}

{phang}{cmdab:ti:tle(}{it:string}{cmd:)} Manually sets the title of the graph.{p_end}

{phang}{cmdab:save(}{it:string}{cmd:)} Sets the filename and the directory to which
	the graph will be set. If the filename ends with no extension or '.gph', it will be
	saved in the graph format. Extensions(png,pdf,tif,wmf,emf,ps,and eps) will be exported.
	Wmf and Emf are only available for the Windows version of Stata. Png and Tif for all
	versions of Stata except Console.{p_end}

{phang}{cmdab:confbarsnone(}{it:varlist}{cmd:)} Removes confidence interval bars
	from only the {it:varlist} listed. The remaining variables in the graphs which
	have not been specified in {cmdab:confbarsnone} will still have the confidence
	interval bars. {p_end}

{phang}{cmdab:yzero} Manually sets the y-axis of the graph to start at zero instead of the Stata default.{p_end}

{marker optslong}
{title:Examples}

{pstd} {hi:Example 1.}

{pmore} {inp:regress} {it:outcomevar treatment_dummy}{break}
		{inp:iegraph} {it:treatment_dummy} , {inp:title({it:"Treatment Effect on Outcome"})}

{pmore}In the example above, there is only two treatment arms (treatment and
		control). {it:treatment_dummy} has a 1 for all treatment observations and
		a 0 for all control observations. The graph will have one bar for control and
		it shows the mean for {it:outcomevar} for all observations in control. The
		second bar in the graph will be the sum of that mean and the coefficient
		for {it:treatment_dummy} in the regression. The graph will also have the
		title: Treatment Effect on Outcome.

{pstd} {hi:Example 2.}

{pmore} {inp:regress} {it:income tmt_1 tmt_2 age education}{inp:, cluster(}{it:district}{inp:)}{break}
		{inp:iegraph} {it:tmt_1 tmt_2}{inp:, noconfbars yzero title({it:"Treatment effect on income"}) }

{pmore}In the example above, the treatment effect on income in reserached. There
		are three treatment arms; control, treatment 1 ({it:tmt_1}) and treatment
		2 ({it:tmt_2}). It is important that no observation has the value 1 in
		both {it:tmt_1} and {it:tmt_2} (i.e. no observation is in more than one
		treatment) and some observations must have the value 0 in both {it:tmt_1}
		and {it:tmt_2} (i.e. control observations). The variables {it:age} and
		{it:education} are covariates (control variables) and is not included
		in {cmd:iegraph}. {inp:noconfbars} omitts the confidence intervall bars
		, and {inp:yzero} sets the y-axis to start at 0.

{pstd} {hi:Example 3.}

{pmore} {inp:regress} {it:chld_wght time treat timeXtreat}{break}
		{inp:iegraph} {it:time treat timeXtreat} {inp:, title({it:"Treatment effect on Child Weight (Diff-in-Diff)"})}

{pmore}In the example above, the data set is a panel data set with two time
		periods and the regression estimates the treatment effect on child weight
		using a Difference-in-Differences model.
		The dummy variable {it:time} indicates if it is time period 0 or 1.
		The dummy variable {it:treat} indicates if the observation is treatment
		or control. {it:timeXtreat} is the interaction term of {it:time}
		and {it:treat}. This the standard way to set up a Difference-in-Differences
		regression model.

{pstd} {hi:Example 4.}

{pmore} {inp:regress} {it:harvest T1 T2 T3 } {break}
		{inp:iegraph} {it:T1 T2 T3} {inp:, title({it:"Treatment effect on harvest"})
		xlabel(,angle(45)) yzero ylabel(minmax) save({it:"$Output/Graph1.gph"})}

{pmore}The example above shows how to save a graph to disk. It also shows that
	most two-way graph options can be used. In this example the {cmd:iegraph}
	option {cdm:yzero} conflicts with the two-way option {cmd:ylabel(minmax)}.
	In such a case the user specified option takes presidence over {cmd:iegraph}
	options like {cdm:yzero}.

{title:Acknowledgements}

{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}Luiza Cardoso De Andrade{break}Michael Orevba{break}Ahmad Zia Wahdat{break}

{title:Authors}

{phang}Kristoffer Bjarkefur & Mrijan Rimal, The World Bank, DECIE

{phang}Please send bug-reports, suggestions and requests for clarifications
		 writing "ietoolkit iegraph" 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"}


iedropone : addin Min to acknowledements

{smcl}
{* 26 Dec 2016}{...}
{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 Leel{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}
{* 26 Dec 2016}{...}
{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}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"}