May 7, 2020

Centering predictor variables in OLS regression

clear clear set seed 1 set obs 1000 // Generate variables generate female = (runiform() > .48) generate health = 1 - female * rnormal(0.5, 1) + 0.1 * rnormal(3, 1) // Recode predictor variable center female recode female (0 = -1), gen(e_female) eststo clear eststo: regress health female eststo: regress health c_female eststo: regress health e_female esttab, cells(b(fmt(2))) rename(c_female female e_female female) /// mtitle("Dummy" "Centering" "Effect") nonumber /// coeflabel(female "Female (ref. male)" _cons "Intercept") /// varwidth(18) collabel("") stats(N, fmt(%9.0gc)) /// title(Comparing different types of centering)

Apr 24, 2020

Random graphs (145): Uncluttered line graphs

// Open General Social Survey data
use wtssall year health1 parsol ///
    if inlist(year, 2002, 2004, 2006, 2010, 2014, 2018) ///
    using "data/GSS7218_R2.DTA", clear

// Listwise deletion
keep if !missing(health1, parsol)

// Fix health variable
recode health1 (4 5   = 1 "Poor health") ///
               (3 2 1 = 0 "Good health"), gen(poorhealth)
label var poorhealth "Poor health"

// Collapse data set
collapse poorhealth [pw = wtssall], by(year parsol)
replace poorhealth = poorhealth * 100

// Create figure
foreach x of numlist 2002 2006 2010 2014 2018 {
 local 2002 gs11
 local 2006 gs11
 local 2010 gs11
 local 2014 gs11
 local 2018 gs11
 local `x'  red
 twoway (line poorhealth parsol if year == 2002, lcolor(`2002') lstyle(solid)) ///
        (line poorhealth parsol if year == 2006, lcolor(`2006') lstyle(solid)) ///
        (line poorhealth parsol if year == 2010, lcolor(`2010') lstyle(solid)) ///
        (line poorhealth parsol if year == 2014, lcolor(`2014') lstyle(solid)) ///
        (line poorhealth parsol if year == 2018, lcolor(`2018') lstyle(solid)) ///
       , title({bf:`x'}, justification(left) bexpand span) ///
         ytitle("% poor health") ///
         xtitle("Living standard compared to parents'") ///
         xlabel(1 `""Much" "better""' ///
                2 `""Somewhat" "better""' ///
                3 `""About" "the same""' ///
                4 `""Somewhat" "worse""' ///
                5 `""Much" "worse""' ///
                , val) ///
         name(year`x', replace) legend(off) nodraw
}

graph combine year2002 ///
              year2006 year2010 ///
              year2014 year2018, ///
      col(2) ysize(8) altshrink ///
      note("{it: Note:} Weighted with WTSSALL", size(vsmall)) ///
      name(figure, replace)

Apr 23, 2020

Random graphs (144): Automatically labeling figures with letters

// Open ESS round 5
use agea stflife cntry if inlist(cntry, "DE", "GB", "NL", "SE") using "ESS5e03_4.dta", clear

// Country variable
kountry cntry, from(iso2c)
rename NAMES_STD country

// Restrict to complete cases
keep if !missing(agea, stflife, cntry)

// Center age
qui sum agea, detail
replace agea = `r(p99)' if agea > `r(p99)' & !missing(agea)
bys country: center agea, gen(age)
drop agea
label var age "Age (centered)"

// Letters
tokenize "`c(ALPHA)'"
local i 1

levelsof country, local(country)

foreach z of local country {
  qui sum age if country == `"`z'"', detail 
  foreach x of numlist 10 25 50 75 90 {
    local x`x': di %9.1f r(p`x')
    di `x`x''
  }
  qui regress stflife c.age##c.age if country == `"`z'"'
  
  qui margins, at(age = (`x10' `x25' `x50' `x75' `x90'))
  marginsplot, title(`"{bf:``i''} `z'"') ///
               ytitle("Life satisfaction" "(predicted)") ///
               xtitle("Age (percentiles)") ///
               xlabel(`x10' "10th" ///
                      `x25' "25th" ///
                      `x50' "50th" ///
                      `x75' "75th" ///
                      `x90' "90th") ///
               ylabel(, format(%6.1f)) ///
               recastci(rarea) ciopts(color(gs10)) ///
               name("``i''", replace) nodraw
  local ++i
}

graph combine A B C D, col(2) ycommon

Mar 24, 2020

Downloading the European Social Survey from within Stata

clear

// Install rcall command
*github install haghish/rcall, stable

// Clear memory of R session
rcall clear

//#install.packages("essurvey");
rcall: library(essurvey)

// Download data
rcall: download_rounds(c(1, 2, 3, 4, 5, 6, 7, 8, 9), ///
                       ess_email = "REGISTERED E-MAIL ADDRESS HERE", ///
                       output_dir = "C:/Users/User/Desktop/ess/data", ///
                       format = 'stata')

Feb 27, 2020

Random graphs (143): Scatterplot

// Open Allbus 1980-2016:
use id03 eastwest year using "allbus\ZA4586_v1-0-0.dta", clear

recode id03 (-1 -7 -8 -9 -13 = .), gen(topbot)
recode eastwest (2 = 1) (1 = 0), gen(east)

table year, c(mean topbot)

collapse topbot, by(year east)

twoway (scatter topbot year if east == 0, connect(L)) ///
       (scatter topbot year if east == 1, connect(L)) ///
      , ylabel(4 (.5) 7, format(%6.1f)) ///
        xlabel(1980 1982 1986 1988 1990 1991 1992 2000 (2) 2016, alt) ///
        xtitle("Survey year") ///
        ytitle("Average ladder ranking") ///
        legend(order(1 "West Germany" 2 "East Germany") pos(11) ring(0)) ///
        note("{it: Source:} German General Social Survey 1980-2016, doi:10.4232/1.13029", justification(left) bexpand span)

Jan 9, 2020

Standard deviation of binary variables

clear

twoway (function y = sqrt(x * (1 - x)), range(0 1)), ///
        ytitle("Sample standard deviation") xtitle("Proportion") ///
        xlabel(0 (.25) 1, format(%6.2f)) ///
        name(figure1, replace)

Nov 25, 2019

Instrumental variable regression

clear
set seed 1
set obs 10000
eststo clear

// Simulate data for IV regression
matrix input c = ( 1, .5, 0, .5\ ///
                  .5,  1, 0,  0\ ///
                   0,  0, 1,  0\ ///
                  .5,  0, 0,  1)
corr2data x u e z, corr(c)

// Calculate y
generate y = 1 + 2*x + 2*u + 5*e

// Without omitted variable bias
eststo: regress y x u

// With omitted variable bias
eststo: regress y x

// Reduced form
eststo: regress y z
local rf = _b[z]

// First stage
eststo: regress x z
local fs = _b[z]
predict xhat
predict xres, resid

// Two-stage predictor substitution (2SPS)
eststo: regress y xhat

// Two-stage residual inclusion (2SRI)
eststo: regress y x xres

// Two-stage least square (2SLS)
eststo: ivregress 2sls y (x = z)

// IV estimate = reduced form/first stage
di `rf'/`fs'

// Table esttab, b(2) se(2) mtitle("DGP" "Bias" "Reduced form" "1st stage" "2SPS" "2SRI" "2SLS") /// coeflabel(x "Predictor x" /// z "Instrument z" /// xres "1st stage residual" /// _cons "Intercept") /// rename(xhat x) drop(u) /// stats(N, label(Observations) fmt(%9.0gc)) /// title(Different varieties of instrumental variable regression) /// varwidth(20)