/*Solutions to exercises in “Stata: a practical introduction” The numbers refer to the numbers in the book ******************************************************** **********************CHAPTER 2************************* ******************************************************** 1: Opens data */ use "C:\temp\Stata\DifferentGoods.dta", clear *2: Describes all variables describe *3: Codebook for all variables codebook *4: Sets -more- off set more off, permanently *5: Codebook again codebook *11: Codebook for gst codebook gst *12 Describes again describe *13: Notes for all variables notes *14: Codebook with notes codebook, notes *15: Opens the data browser browse *19: Sorts the data after accending values of -recycle- sort recycle *20: Frequency distribution for elecsystem tabulate elecsystem *21: Frequency distribution for elecsystem including missing values tabulate elecsystem, missing *23: Frequency distribution for elecsystem without labels tabulate elecsystem, missing nolabel *24: Codebook for elecsystem codebook elecsystem *25: Frequency distribution for three variables tab1 eu seaaccess recycle *26: Inspecting all variable inspect *27: Histogram for recycle histogram recycle, frequency *29: summarize //summarize for all variables with default readout summarize, detail //summarize including additional statistics *30: Repeats some commands *a) summarize, detail *b) inspect *c) Histogram for organic histogram organic, frequency *d) Codebook codebook *32: *a) Transfers the use and the describe command use "C:\temp\Stata\DifferentGoods.dta", clear describe *b) Histogram for gdpcap histogram gdpcap, frequency *35: Saves the dataset with the name DifferentGoodsCh2.dta save "C:\temp\Stata\DifferentGoodsCh2.dta" *37: Opens the help for codebook help codebook *39: Opens the help file for summarize help summarize * Opens the dialogue box for codebook db codebook *40: Opens the help file for codebook help codebook ***************************************************** *********************CHAPTER 3*********************** ***************************************************** *43: Opens data from previous chapter use "C:\temp\Stata\DifferentGoodsCh2.dta", clear *45: Assigns labels to urban and female label variable urban "Urbanization" label variable female "Females' share of population" *46 b): Assigns labels to education label variable education "Tertiary education (share)" *47: *a) Assigns note to -frac- notes frac: Ethnic fractionalization (late 1990s) from Alesina et al. 2003 *b) Assigns label label variable frac "Ethnic fractionalization" *c) Edits the note notes replace education in 1: Share of population above 25 with a tertiary education (in 2001) *48: Shows existing value labels label list *49: Assigns noyesLB to -eu- label values eu noyesLB *50: Generates random1, random2, text and welfarestate generate random1 = . //a) generate random2 = . //a) generate str text = "" //b) generate byte welfarestate = . //c) browse //d) codebook random1 random2 text welfarestate //d) *51: Enters numbers and text replace random1 = 1.1 in 1 replace random1 = 2.2 in 2 replace random2 = 1.2 in 1 replace random2 = 1.3 in 2 replace text = "test" in 1 replace text = "retest" in 2 *52: Generates value label with the name welfareLB label define welfareLB 1 "Conservative" 2 "Liberal" 3 "Socialdemocratic" //a) label values welfarestate welfareLB // b) assign the label to the variable welfaresate describe welfarestate // c) check with describe *53: *a): Enters data replace welfarestate = 1 in 1 replace welfarestate = 1 in 2 replace welfarestate = 1 in 7 replace welfarestate = 1 in 8 replace welfarestate = 1 in 9 replace welfarestate = 1 in 14 replace welfarestate = 1 in 26 replace welfarestate = 1 in 17 replace welfarestate = 2 in 13 replace welfarestate = 2 in 27 replace welfarestate = 3 in 5 replace welfarestate = 3 in 18 replace welfarestate = 3 in 25 *b) Assigns value label label variable welfarestate "Welfare state regime" *c): Assigns note notes welfarestate: Data are entered 07.10.2014. Source: Esping-Andersen, The three world of welfare capitalism, 1990. *54: Deletes variables drop random1 random2 text *55: Summarize for gst, git, pm4 and gdpcap; ordered with a hyphen summarize gst-gdpcap *56: *a) Saves the dataset with a new name save "C:\temp\Stata\DifferentGoodsCh3.dta" *b) Deletes observations that are not categorized socialdemocratic drop if welfarestate !=3 *d) Finds GDP per capita summarize gdpcap *e) Opens the saved dataset use "C:\temp\Stata\DifferentGoodsCh3.dta",clear *57: Finds average GDP for socialdemocratic countries summarize gdpcap if welfarestate==3 ***************************************************** *********************KAPITEL 4*********************** ***************************************************** *58: use "C:\temp\stata\DanishElectionStudy2005.dta", clear // a+b) opens data set describe //c) describes data browse //d) dpens the data matrix *59: Seaches for information about gender lookfor sex gender *60: generate gender1 = v312 //a) copies v312 to gender1 codebook v312 gender1 //b) codebook *61: clonevar gender = v312 //a) copies using clonevar codebook v312 gender* //b) codebook drop gender1 //c) deletes gender1 *62: Moves gender to the beginning of the dataset order gender *63: Opens the dialogue box for codebook db codebook *64: Dialogue box for recode is found under "Data > Create or change data > Other variable-transformation commands > Recode categorical variable" *65: Codebook for the variable gender codebook gender *66: recode gender (2=0), generate(male) //recodes gender to male codebook male //codebook for male *67: Cross tabulation between gender and male tabulate gender male *68: drop male //a) deletes male recode gender (1=1 "Male") (2=0 "Female"), generate(male) label(FeMaLB) //b) recodes and assigns labels codebook male //c) *69: codebook v314,ta(100) //a) inspects coding recode v314 (1=1 "Denmark") (2 3 10 = 2 "Western") (nonmissing = 3 "Non-Western"), gen(birthplace) label(birthLB) //a)recodes and assigns value labels label variable birthplace "Country of birth, 3 categories" // c) assigns variable lables tabulate v314 birthplace //d) inspects the recoding *70: codebook v20, tabulate (100) // a) inspects the coding of v20 recode v20 (1 2 5 7 10 = 0 "Red") (3 4 6 8 9=1 "Blue") (nonmissing=.), generate(blue) label(rbLB) //a) recodes and assigns value labels label variable blue "Red/blue vote" //b) assigns variable labels tabulate blue //c) examines the distribution of votes *71: Frequency distribution of v20 tabulate v20 *72: Inspects partychoice tabulate partychoice codebook partychoice, tabulate(100) *73: codebook v351, tabulate (100) //a) shows information about v351 recode v351 (14 = .a) (15=.b) (16=.c) (17=.d) (18=.e) (19=.f), generate(partychoicetoday) //a) recodes the values 14-19 to missing label copy V351 PaChToDLB //b) copies the value label to PaChToDLB label values partychoicetoday PaChToDLB //c) assigns the label to the variable *74: label define PaChToDLB 1 "Social Democrats" 2 "Social Liberals" 3 "Conservatives" 4 "Centre Democrats" 5 "Socialist People’s Party" /// 6 "Christian Democrats" 7 "Minority Party" 8 "Danish People’s Party" 9 "Liberals" 10 "Leftwing Alliance" /// 11 "Unaffiliated candidate" 13 "Other party" .a "Voted blank" .b "Don’t remember" .c "Decline" .d "Will not vote" /// .e "Ineligible to vote" .f "Other", replace //a) edits all value labels codebook partychoicetoday, tabulate(100) //b) codebook *75: codebook v188 v195 v224 v226 //a) inspects the variables with the codebook recode v188 v224 v226 (1=5) (2=4) (4=2) (5=1) (8=.), generate (intol1 intol3 intol4) //b) reverses the coding and code out missing recode v195 (8=.), generate(intol2) //b) codes out missing tab1 intol* //c) inspects the distributions; it appears that v222 about expulsions causes the most sceptical attitudes towards immigrants *76: codebook v137-v144 // inspects the variables recode v137-v144 (1=0) (2=1) (3=.a) (8=.b), prefix(agreeB_) // recodes to agreeB_v137 etc *77: Recodes v357 to a four-part variable inckluding value labels and a variable label recode v357 (65/100 = 4 "65+") (50/65 = 3 "50-64") (30/50=2 "30-49") (1/30=1 "<30"), generate(age4cat) label variable age4cat "Age, 4 categories" *78: tabulate v357 //a) frequency distribution for age tabulate partychoicetoday if v357 == 17, missing //b) frequency distribution for parchoicetoday for 17-years-olds including missing values *79: clonevar partychoicetoday20 = partychoicetoday // copies to a new variable replace partychoicetoday20 = .e if v357 < 20 // recodes for respondents under 20 years of age *80: codebook male v357 // codebook for variable clonevar partychoicetoday_male30 = partychoicetoday // creates partychoicetoday_male30 as a copy of partychoicetoday replace partychoicetoday_male30 = .e if male==1 & v357 <30 // replaces with .e if the respondent is a male and under 30 years of age *81 tabulate partychoice, generate(party) //a) browse partychoice party1-party11 //b) *85: Saves the data set with a new name save "C:\temp\stata\Election05Ch4.dta" ***************************************************** *********************CHAPTER 5*********************** ***************************************************** *86: Starts log capture log close log using "C:\temp\Stata\Ch5", text replace *87: Searches for catplot search catplot *88: Searches for gr0002_03 search gr0002_03 *89: Opens the data set use "C:\temp\Stata\Election05Ch4.dta", clear *90: Frequency distribuion for partychoicetoday tabulate partychoicetoday *91: graph pie, over(partychoice) note(Source: Danish Election Study 2005) //a) pie chart in colours graph pie, over(partychoice) sort(blue) note(Source: Danish Election Study 2005) //b) sorted by support *92: Catplot for partychoice catplot partychoice,percent *93: Histogram for partychoice histogram partychoice, discrete percent *94: Histogram with distance histogram partychoice, discrete percent gap(10) *95: Changes the Y-label and adds a line at 2 percent histogram partychoice, discrete percent gap(10) ytitle(Vote Share (%)) yline(2, lpattern(dash)) *96: Includes party names histogram partychoice, discrete percent gap(10) ytitle(Vote Share (%)) yline(2, lpattern(dash)) xlabel(, valuelabel) *97: Includes all party names histogram partychoice, discrete percent gap(10) ytitle(Vote Share (%)) yline(2, lpattern(dash)) xlabel(1(1)11, valuelabel) *98: Rotates labels histogram partychoice, discrete percent gap(10) ytitle(Vote Share (%)) yline(2, lpattern(dash)) xlabel(1(1)11, angle(forty_five) valuelabel) *99: Removes label on the X-axis and adds notes histogram partychoice, discrete percent gap(10) ytitle(Vote Share (%)) yline(2, lpattern(dash)) xtitle("") xlabel(1(1)11, angle(forty_five) valuelabel) note(The dotted line represents the barrier for representation; Source: Danish Election Study 2005) scheme(Lean2) *100: Splits the previous command so it is easier to read histogram partychoice, discrete percent gap(10) ytitle(Vote share (%)) yline(2, lpattern(dash)) xtitle("") /// xlabel(1(1)11, angle(forty_five) valuelabel) note(The dotted line represents the barrier for representation; Source: Danish Election Study 2005) scheme(Lean2) *101: Creates dummy variables on the basis of partychoicetoday tabulate partychoicetoday, generate(partytd) *102: ci partytd3, binomial //a) 95% confidence interval for the proportion of the observations that answer that they will vote for Conservatives bitest partytd6==0.02 //b) test examining whether the part of the observations informing that they will vote for Conservatives equals 2 percent *103: codebook v252, tabulate(20) //a) codebook for v252; tabulate(20) entails that a frequency distribution is shown even though there are more than 10 unique values recode v252 (88=.), generate(lrplacement) //b) recodes to lrplacement, where Don't know is coded as missing summarize lrplacement, detail //c) summarize for lrplacement *104: Descriptive statistics for lrplacement and v357 tabstat lrplacement v357, statistics( mean iqr ) columns(variables) *105: histogram lrplacement // histogram for lrplacement, continuous specification histogram lrplacement, discrete // histogram for lrplacement, discrete specification *106: 4 histograms with different scales on the Y-axis histogram lrplacement, discrete histogram lrplacement, discrete fraction histogram lrplacement, discrete frequency histogram lrplacement, discrete percent *107: ci lrplacement //a) 95% confidence interval ci lrplacement,level(99) //a) 99% confidence interval ttest lrplacement == 5 //b) t-test of whether the mean for lrplacement equals 5 *108: Saves log close //b) closes the log file save "C:\temp\Stata\Election05Ch5.dta" //c) saves data *109: Repeats excercise 90 tabulate partychoicetoday ***************************************************** *********************CHAPTER 6*********************** ***************************************************** *113: capture log close log using "C:\temp\Stata\Ch6", text replace use "C:\temp\Stata\Election05Ch5.dta", clear // opens the data set db tabulate2 // dialogue box for cross tablulation *114: codebook v180 recode v180 (1=0 "tax cuts") (2=1 "service") (8=.), generate(service) label(serviceLB) // recodes and assigns value labels lab var service "Service (vs. tax cuts)" // assigns value labels tabulate service male // cross tabulation *115: Cross tabulation with relativ (column) frequences tabulate service male, column *116: Catplot catplot service male, percent(male) scheme(lean2) catplot service male, percent(male) stack asyvars scheme(lean2) *117: Comparison of the proportions for the two groups prtest service, by(male) *118: Cross tabulation of male and partychoice tabulate partychoice male, column *119: net install lambda, from(http://fmwww.bc.edu/RePEc/bocode/l) //a installs lambda lambda partychoice male //b *120: Catplot for male and partychoice catplot male partychoice, percent(male) //a *121: Chi2-test for male and partychoice tabulate partychoice male, chi2 column *122: tabulate blue v335,column //a catplot blue v335, percent(v335) //c *123: catplot blue v335, percent(v335) asyvars stack scheme(lean2) //a catplot blue v335, percent(v335) asyvars stack //b *124: As excercise 123 but with specified colours catplot blue v335, percent(v335) asyvars stack bar(1, color(red)) bar(2,color(blue)) *125: Gamma and tau-b tabulate rc_v188 age4cat, colum gamma taub *126: Catplot for age4cat and v188 catplot v188 age4cat, percent(age4cat) asyvars stack scheme(lean2) *127: Dotplot for male and lrplacement graph dot lrplacement, over(male) scheme(lean2) *128: Dotplot from exercise 127 with modifications graph dot (mean) lrplacement , over(male) scheme(lean2) exclude0 yscale(range(5 6)) /// ylabel(5(0.2)6) ytitle("lrplacement, mean") *129: ttest for male and lrplacement ttest lrplacement, by(male) *130: Test of variance homogeneity robvar lrplacement, by(male) *131: recode v337 (8=.) //a mean lrplacement, over(v337) //b *132: graph dot (mean) lrplacement , over(v337) scheme(lean2) exclude0 yscale(range(4.6 6.2)) /// ylabel(4.6(0.2)6.2) ytitle("Mean, lrplacement") *133: oneway lrplacement v337,tabulate *134: correlate lrplacement v357 pwcorr lrplacement v357 *135: correlate intol* pwcorr intol*, obs pwcorr intol*, obs listwise *136: Pairwise correlation with significance test pwcorr lrplacement v357, sig *137: Scatterplot scatter lrplacement v357 *138: Sunflower-plot sunflower lrplacement v357 *139: save C:\temp\Stata\Election05Ch6.dta // saves tge data set use C:\temp\Stata\DifferentGoodsCh3.dta // opens the data set *140: Scatterplot scatter gst git //a) scatterplot pwcorr gst git,sig //b) correlation and P-value *141: Scatterplot using the menu twoway (scatter gst git) *142: Same plot, but with country names twoway (scatter gst git, mlabel(country)) *143: twoway (scatter gst git, mlabel(country)) (lfit gst git) // as before but with OLS line twoway (scatter gst frac, mlabel(country)) (lfit gst frac) // new variables *144: Same plots, with names twoway (scatter gst git, mlabel(country)) (lfit gst git) , name(scat_gst_git) twoway (scatter gst frac, mlabel(country)) (lfit gst frac) , name(scat_gst_frac) *145: set autotabgraphs on, permanently // requests graphs on tabs instead of separate windows twoway (scatter gst git, mlabel(country)) (lfit gst git) , name(scat_gst_git, replace) twoway (scatter gst frac, mlabel(country)) (lfit gst frac) , name(scat_gst_frac, replace) *147: Confidence intervals with three sample sizes cii 250 0.52 cii 500 0.52 cii 1000 0.52 *148: Gamma coefficient for the correlation between var3 and var4 tabi 30 20 \ 40 10 \ 45 5, gamma *149: Opens the help file for tabulate h tabulate twoway *150: use "C:\temp\Stata\Election05Ch6.dta", clear //a tab service male, gamma taub //b return list //c *151: Calculates gamma display r(gamma) *152: Calculates gamme with standard errors display r(gamma)/r(ase_gam) *153: Calculates P-value and tau-b display normal(r(taub)/r(ase_taub)) log close ***************************************************** *********************CHAPTER 7*********************** ***************************************************** *154: Stats logging and opens data capture log close log using "C:\temp\Stata\Ch7", text replace use "C:\temp\Stata\Election05Ch6.dta", clear *155: Codebook codebook rc_v184 rc_v188 rc_v195 rc_v224 rc_v226 *156: recode rc_v184 (1=1) (2=3) (3=5) //recodes rc_v184 to new range of variation recode rc_v188 rc_v224 rc_v226 (1=5) (2=4) (3=3) (4=2) (5=1) //reverses items *157: Item-item-analyses with gamma and Pearsons' r tab2 rc_*,gamma pwcorr rc_* *158: Reliability test alpha rc_* , item casewise *159: Creates -tempindex-; only observations with at eleast two valid values are assigned a value alpha rc_* , min(2) generate(tempscale) item *160: su tempscale //summarize for the index generate intolerance = ((tempscale-1)/(5-1))*100 //rescales, so the range of the new index is 0-100 *161: sum intolerance,detail //summarize for the index histogram intolerance //histogram drop tempscale //deletes tempscale *162 foreach var in v188 v195 { recode `var' (8=.a),generate(`var'mis) sum `var'mis replace `var'mis = r(mean) if `var'mis ==.a } *163: deletes variables and saves data drop v188mis v195mis save "C:\temp\Stata\Election05Ch7.dta" log close ***************************************************** *********************CHAPTER 8*********************** ***************************************************** *164: Starts log and opens data capture log close log using "C:\temp\Stata\Ch8", text replace use "C:\temp\Stata\Election05Ch7.dta", clear *165: Bivariate regression reg intolerance v357 *166: reg intolerance v357, beta //as previously but reporting beta pwcorr intolerance v357, sig obs //Pearsons' r *167: reg intolerance male //estimates intolerance for men and women using regress ttest intolerance, by(male) // as above but using ttest *168: tab v337, generate(durban) //creates dummyvariabes reg intolerance durban2-durban5 //the correlation between urbanisation and intolerance using regress and dimmyvariables *169: reg intolerance i.v337 //as previously but with factor variables *170 testparm i.v337 *171 reg intolerance ib(3).v337 //as excercise 169 but with category number 3 as reference *172: codebook v314,tabulate(25) recode v314 (1=1 native) (nonmis=0 immigrant),generate(native) *173: reg intolerance v357 i.native i.male *174: reg intolerance v357 i.native i.male,robust *175: reg intolerance i.highschool //model 1 reg intolerance i.highschool v357 i.native i.male //model 2 reg intolerance i.highschool v357 i.native i.male i.v337 //model 3 *176 reg intolerance i.highschool v357 i.native i.male i.v337 //model 3 reg intolerance i.highschool v357 i.native i.male if e(sample) == 1 //model 2 reg intolerance i.highschool if e(sample)==1 //model 1 *177 reg intolerance i.highschool v357 i.native i.male i.v337 eststo m3 reg intolerance i.highschool v357 i.native i.male if e(sample) == 1 eststo m2 reg intolerance i.highschool if e(sample)==1 eststo m1 esttab m1 m2 m3 *178 esttab m1 m2 m3 using tabel1, r2 ar2 se replace *180 regress intolerance i.male v357 i.v337 //a margins v337, pwcompare(effects) //b margins v337, pwcompare(effects) nofvlabel //b *181 margins v337, pwcompare(effects groups) *182 margins v337, at((mean) _c male=0) save "C:\temp\Stata\Election05Ch8.dta" *183 net install gr0056, from(http://www.stata-journal.com/software/sj13-3) net install coefplot, from(http://fmwww.bc.edu/RePEc/bocode/c) *184 *top graph in Figure 8.2 regress intolerance i.male v357 i.v337 //the regression margins v337 //estimates adjusted means marginsplot, /// recast(scatter) ///removes lines between points ytitle(Intolerance) ///changes the title on the Y axis xtitle ("") ///removes the title on the x-axis xlabel(, angle(20)) ///turns labels on the X axis 20 degrees title("") ///removes overall title scheme(s1mono) ///changes scheme plotregion(style(none)) /// removes top and right frame note("Estimates with 95% confidence intervals") //adds note *Bottom graph in Figure 8.2 regress intolerance i.male v357 i.v337 //the regression margins v337, pwcompare(effects) //calculates predicted differences marginsplot, /// horizontal unique recast(scatter) yscale(reverse) /// difficult to explain.. xline(0) ///inserts vertical line ytitle(Comparisons) /// changes the title on the Y axis title("") ///removes the title xtitle(Difference) ///changes the title on the X axis note("95 % confidence intervals""Groups: 1: Rural, 2: Town, <10.000" /// add notes "3: Town, 10-50.000, 4: Town, 50-500.000, 5: Metropolitan area",span) /// do ///span moves the note all the way to the left plotregion(style(none)) /// removes top and right frame scheme(s1mono) //changes scheme *Commands for figure 8.3 (Not an exercise) regress intolerance i.male v357 //the regression marginscontplot v357, /// ci ///calls up the confidence interval plotopts(ytitle("Intolerance") xtitle("Age (years)") ///changes the title on the X and Y axes scheme(s1mono) ///changes scheme plotregion(style(none))) //removes top and right frame *185 regress intolerance i.male v357 //the regression marginscontplot v357, at1(18 (2) 80) /// ci ///adds the confidence interval plotopts(ytitle("Intolerance") xtitle("Age (years)") ///changes the title on the X and Y axes scheme(s1mono) ///changes scheme plotregion(style(none))) //removes top and right frame *commands for Figure 8.4 (not an exercise) reg intolerance i.male v357 i.native //the regression marginscontplot v357 male, /// plotopts(ytitle("Intolerance") xtitle("Age (years)") ///changes the title on the X & Y axes legend(ring(0) ///moves the explanation inside the graph lab(1 "Female") lab(2 "Male")) ///changes labels in the explanation note("The control variable 'country of birth' is held at the observed values", placement(center)) ///centers note scheme(lean1)) //changes scheme *186 reg intolerance i.male v357 i.native //the regression marginscontplot v357 male *187 reg intolerance i.highschool v357 i.native i.male i.v337 eststo m3 reg intolerance i.highschool v357 i.native i.male if e(sample) == 1 eststo m2 reg intolerance i.highschool if e(sample)==1 eststo m1 coefplot /// starts coefplot (m1,label("Without control")) ///labels model 1 (m2,label("Controls: gender, age and country of birth")) ///labels model 2 (m3,label("+urbanisation")), ///labels model 3 keep(1.highschool) ///see explanation above vertical ///specifies that the plot is to be vertical level(99 95) scheme(s1mono) ///specifies confidence intervals and scheme legend(row(1)) ///specifies that the explanation is to be kept on a single row ytitle("Coefficient, education") xlabel("") ///adds and removes titles on the axes note("Confidence intervals: 95% (broad) 99% (narrow)",placement(center)) //adds note, centred *Simple edition coefplot m1 m2 m3, keep(1.highschool) ***************************************************** *********************CHAPTER 9*********************** ***************************************************** *188: capture log close log using "C:\temp\Stata\Ch9", text replace //a)starts log use "C:\temp\Stata\election05Ch8",clear //a)opens data reg intolerance v357 male //b) the regression acprplot v357, lowess //c) acpr-plot for age *189: Leverage-versus-residual-squared-plot lvr2plot *190: predict tempcooksd, cooksd //calculates cook's d display 4/e(N) //calculates critical value summarize tempcooksd if tempcooksd >(4/e(N)) //sums observation with critical values *191 browse if tempcooksd >(4/e(N)) & tempcooksd <. *192: avplots avplots *193: DFBETA predict tempdfbeta, dfbeta(v357) //a summarize tempdfbeta if abs(tempdfbeta) > 2/sqrt(e(N)) //b *194: Histogram *Calculation of residuals, is saved as the variable -tempresid- predict tempresid, residuals *Histogram, including normal curve for the distribution of the residuals histogram tempresid, normal *195: q-q-plot qnorm tempresid *196: rvfplot,yline(0) //rvfplot rvpplot v357, yline(0) rvpplot male, yline(0) *197: White's test estat imtest,white *198: VIF vif *199: drop temp* //cleaning up *200 generate intol101 = intolerance + 1 //a) rescales intolerance generate lnintol = ln(intol101) //a)transformes intol101 regress lnintol v357 i.male //b) logaritmic regression regress intolerance c.v357##c.v357 i.male //c)quadratic regression *201 marginscontplot v357, ci /// plotopts(ytitle("Intolerance") xtitle("Age (years)") scheme(s1mono)) save "C:\temp\Stata\Election05Ch9.dta" //saves data set log close ***************************************************** *********************CHAPTER 10********************** ***************************************************** *202: Opens data capture log close log using "C:\temp\Stata\Ch10", text replace use "C:\temp\Stata\GrowthCh10.dta", clear *203: The regression model reg meangrowth aidcap goodgov initial forinvest eduyears,robust //without interaction reg meangrowth aidcap goodgov c.aidcap#c.goodgov initial forinvest eduyears,robust //with interaction *204: Statistics for the variables from the previous regression based on the estimation sample estat summarize *205: Calculation of average marginal effects margins, dydx(aidcap) at(goodgov=(-1.8(0.2)1.8)) vsquish *206: Margins plot marginsplot *207: The commands for Figure 10.5 marginsplot, ///starts the command marginsplot recast(line) ///line rather than points recastci(rline) ///specifies that the confidence interval should also be drawn with lines ciopts(lpattern(dash)) ///specifies that the confidence interval is to be drawn with dotted lines yline(0) ///inserts a line y=0 xlabel(#5) ///adjusts the amount of numbers on the x axis downwards legend(on ///shows explanation label(1 "95% Confidence Interval") ///specifies the explanation label(2 "Marginal effect")) ///specifies the explanation xtitle(Institutional quality) ///inserts alternative title on the x axis ytitle("Marginal effect of development aid") ///inserts alternative title on the y axis title("") ///removes the overall title plotregion(style(none)) ///removes upper and right frame scheme(s1mono) //optimises for black/white display *208 summarize goodgov if e(sample),detail margins, dydx(aidcap) at(goodgov=(`r(p10)' `r(p50)' `r(p90)')) *209 sum goodgov if e(sample),detail margins, at(aidcap=(0 130) goodgov=(`r(p10)' `r(p50)' `r(p90)')) marginsplot, noci *The commands for Figure 10.4 (not an exercise) marginsplot, noci ///marginsplot without confidence intervals recast(line) ///removes the points ytitle("Average annual growth (%)") ///changes the title on the on Y axis xtitle("Aid per capita ($)") ///changes the title on the on X axis title("") ///removes the overall title legend (order(3 2 1) ///changes explanations label(1 "Low institutional quality *") /// label(2 "Medium institutional quality *") /// label(3 "High institutional quality *")) /// note("*: P< 0.05""Low, Medium, High institutional quality: 10th, 50th and 90th percentile" /// "Control variables are kept at their observed values") ///adds notes plotregion(style(none)) ///remove upper and right frame scheme(s1mono) //changes scheme *210 summarize goodgov if e(sample),detail margins, dydx(aidcap) at(goodgov=(`r(min)' `r(mean)' `r(max)')) sum goodgov if e(sample),detail margins, at(aidcap=(0 130) goodgov=(`r(min)' `r(mean)' `r(max)')) marginsplot, noci ///marginsplot without confidence intervals recast(line) ///removes the points ytitle("Average annual growth (%)") ///changes the title on the on Y axis xtitle("Aid per capita ($)") /// changes the title on the on X axis title("") ///removes the overall title legend (order(3 2 1) ///changes explanations label(1 "Minimum institutional quality *") /// label(2 "Mean institutional quality *") /// label(3 "Maximum institutional quality *")) /// note("*: P< 0.05" /// "Control variables are kept at their observed values") ///adds notes plotregion(style(none)) ///remove upper and right frame scheme(s1mono) //changes scheme *The commands for Figure 10.6 (not an exercise) reg meangrowth c.aidcap##goodgov01 initial forinvest eduyears,robust //the regression margins, dydx(aidcap) over(goodgov01) //marginal effects marginsplot, ///marginsplot recast(scatter) /// points instead of line yline(0) ///inserts line at Y=0 xscale(range(-0.5 1.5)) ///expands the range for the X axis xtitle("Quality of Institutions") ///changes the title on the X axis ytitle(Marginal effect of Foreign aid) ///changes the title on the Y axis title("") ///removes the overall title plotregion(style(none)) ///removes upper and right frame scheme(s1mono) //changes scheme *The commands for Figure 10.7 (not an exercise) reg meangrowth i.aidcap01##c.goodgov initial forinvest eduyears,robust //the regression margins, dydx(aidcap01) at(goodgov=(-1.8(0.2)1.8)) //marginal effects marginsplot , /// recast(line) ///asks for a line rather than points recastci(rline) ///specifies that the confidence interval is also to be drawn with lines ciopts(lpattern(dash)) ///specifies that the confidence interval is to be drawn with dotted lines yline(0) ///inserts a line at y=0 xlabel(#5) ///adjusts the number of numbers on the x axis downwards legend(on ///asks for an explanation to be shown label(1 "95% Confidence interval") ///specifies the explanation label(2 "Marginal effect")) ///specifies the explanation xtitle("Quality of institutions") ///inserts alternative title on the x axis ytitle("Marginal effect of aid on growth""(Difference between heavy and light receivers)") /// title("") ///remove the overall title plotregion(style(none)) ///removes upper and right frame scheme(s1mono) //optimises for black/white display log close ***************************************************** *********************CHAPTER 11********************** ***************************************************** *211 net install spost9_ado, from(http://www.indiana.edu/~jslsoc/stata) *212 capture log close log using "C:\temp\Stata\Ch11", text replace use "C:\temp\Stata\election05Ch9",clear *213 codebook blue *214 codebook male v357 v337 v334 intolerance,tabulate(100) //a recode v334 (88=.) //b *215 logit blue i.male v357 i.v337 v334 intolerance *216 fitstat *217 margins, dydx(*) *218 margins, dydx(*) atmeans *219 margins, dydx(*) at(male=1 v337=3) atmeans //a margins, dydx(*) at(male=1 v337=1) atmeans //b *220 margins, at((p25) intolerance) at((p75) intolerance) *221 margins v337 *222 logit blue i.male v357 v334 i.v337 intolerance,or //method 1 listcoef //method 4 *223 listcoef, reverse *224 marginscontplot intolerance, ci *225 - the command for Figure 11.1 summarize intolerance if e(sample), detail //calculates percentiles marginscontplot intolerance, ci /// plotopts /// (ytitle("Ave. predicted probability for blue vote") ///changes the title on the Y axis xtitle("Intolerance") ///changes the title on the X axis xline(`r(p25)' `r(p75)') ///inserts vertical lines note("Notes: 95% confidence interval. The vertical lines represent the 25th and 75th percentiles") /// plotregion(style(none)) ///removes upper and right frame scheme(s1mono)) *226 margins v337 marginsplot *227 margins v337 marginsplot, /// recast(scatter) ///removes lines between points ytitle(Average predicted probability for blue votes) ///changes the title on the Y axis xlabel(, labsize(vsmall) angle(forty_five)) ///reduces size of and turn labels xtitle(Urbanisation) ///changes the title on the X axis xscale(range(0.5 5.5)) ///extends the X axis title("") //removes title *228 logit blue intolerance predict tempprop1 twoway (lowess blue intolerance) (line tempprop1 intolerance,sort) *229 logit blue lnintol predict tempprop2 twoway (lowess blue lnintol) (line tempprop2 lnintol,sort) *230 logit blue i.male v357 v334 i.v337 intolerance summarize intolerance if e(sample)==1 generate tempvar = autocode(intolerance, 10, r(min), r(max)) egen ordvar1 = group(tempvar) logit blue i.male v357 v334 i.v337 i.ordvar margins ordvar,predict(xb) marginsplot drop tempvar log close ***************** ***Appendix E*** ***************** *E1 use "C:\temp\Stata\Election05Ch6.dta",clear //a codebook blue male rc_v188 //b *E2 tabulate blue rc_v188,gamma //a bysort male: tabulate blue rc_v188,gamma //b *E3 catplot blue rc_v188, percent(rc_v188 male) over(male) asyvars stack ***************** ***Appendix F*** ***************** *F1 use "C:\temp\Stata\Election05Ch6.dta" //a recode rc_v184 (1=1) (2=3) (3=5) //b) recodes rc_v182 to new range recode rc_v188 rc_v224 rc_v226 (1=5) (2=4) (3=3) (4=2) (5=1) //b) reverses items //c: gen Src_v184 = rc_v188 + rc_v195 + rc_v224 + rc_v226 gen Src_v188 = rc_v184 + rc_v195 + rc_v224 + rc_v226 gen Src_v195 = rc_v184 + rc_v188 + rc_v224 + rc_v226 gen Src_v224 = rc_v184 + rc_v188 + rc_v195 + rc_v226 gen Src_v226 = rc_v184 + rc_v188 + rc_v195 + rc_v224 foreach var in rc_v188 rc_v195 rc_v224 rc_v226 { tabulate S`var' `var', gamma nofreq } alpha rc_v184 rc_v188 rc_v195 rc_v224 rc_v226, casewise item //d