** STATA TRAINING 4 ** cd "Q:\My Drive\HEAL_LAB\STATA Training\Training 4\data sets" *** Objective 1: Append and Merge *** ** APPEND ** * Step 1: import the excel files and save as STATA * import excel using "dallas 2014.xlsx", clear first save dallas_2014, replace import excel using "dallas 2015.xlsx" , clear first save dallas_2015, replace import excel using "dallas 2016.xlsx" , clear first save dallas_2016, replace * Step 2: append the data sets * use dallas_2014, clear append using dallas_2015 dallas_2016 * Step 3: save the new data set * save dallas_2014_2016, replace ** MERGE ** * Step 0: save using data set into STATA format * import excel using dallas_rain.xlsx, clear first save dallas_rain, replace * Step 1: load master data set * use dallas_2014, clear * Step 2: merge * merge 1:1 month year using dallas_rain keep if _merge==3 save dallas_rain_2014, replace ** Merge with all years of data ** use dallas_2014_2016, clear merge 1:1 month year using dallas_rain tab _merge keep if _merge==3 save dallas_rain_all_years, replace *** Objective 2: Loops *** * how to loop over numbers * forvalues i=2014/2016 { import excel using "dallas `i'.xlsx", clear first save dallas_`i', replace } * how to loop over words * foreach x in allen arlington dallas irving { import excel using `x'.xlsx, clear first save `x', replace } append using dallas arlington allen * how to loop-de-doo or loop within a loop * foreach x in allen arlington dallas irving { forvalues i=2014/2016 { import excel using `x'.xlsx, clear first sh("`i'") save `x'_loop_`i', replace } } use allen_loop_2014, clear append using allen_loop_2015 allen_loop_2016 arlington_loop_2014 arlington_loop_2015 arlington_loop_2016 dallas_loop_2014 dallas_loop_2015 dallas_loop_2016 irving_loop_2014 irving_loop_2015 irving_loop_2016