*********************************************************** *** Stata Tutorial Session Four: Automation and Programming * Sample dofile * Yiming Cao * Boston University * Oct 2, 2019 *********************************************************** ********************************* *** PART 1: Working with dofiles ********************************* // 1. To start the dofile editor, type: doedit // 2. Write the commands for the first steps: clear all // clear everything from the memory cd d:/Stata // change directory capture log close // close existing log files, if any log using week4,text replace // open a log file sysuse auto,clear // open the dataset // 3. Comments in Stata dofiles: * I am a comment // I am also a comment describe // I can comment at the end of a line describe /* me too */ /* And I can comment multiple lines */ // 4. Long lines in Stata dofiles: twoway (scatter mpg weight if foreign==0,msymbol(O) mcolor(black)) /// (scatter mpg weight if foreign==1,msymbol(X) mcolor(black)) /// ,legend(label(1 "Domestic") label(2 "Foreign")) /// title("Mileages and Weight") #delimit ; twoway (scatter mpg weight if foreign==0,msymbol(O) mcolor(black)) (scatter mpg weight if foreign==1,msymbol(X) mcolor(black)) ,legend(label(1 "Domestic") label(2 "Foreign")) title("Mileages and Weight"); #delimit cr // 5. Debugging // the following command will produce an error // because there is no variable called mmake: list mmake // you can ignore it by: capture list mmake ************************************************************ *** PART 2: Programming essentials ************************************************************ // 1. Macros local i=1 local i=`i'+1 di `i' di "i equals to `i'" local controls weight length foreign reg price mpg `controls' global controls weight length foreign reg price mpg $controls summarize price local pm=r(mean) di `pm' // 2. Loops forvalues i=1/5 { di `i' list make price in `i' } foreach v of varlist weight length foreign { reg price mpg `v' } // 3. Conditional Execution forvalues i=1/10 { *list make in `i' di make[`i'] if `i'>=5 continue,break } log close