Showing posts with label International Social Survey Program. Show all posts
Showing posts with label International Social Survey Program. Show all posts

Aug 2, 2018

Meta-regression

// Open ISSP 2005
use COUNTRY WRKHRS V51 using "ZA4350_v2-0-0.dta", clear

// Prepare variables
rename COUNTRY country
  // Job satisfaction
generate jobsatis = 7 - V51
rename WRKHRS workhrs
  // Average working hours per country
bys country: egen avghrs = mean(workhrs)
  // Center working hours
center workhrs, inplace

// Fit models
eststo clear
eststo: regress jobsatis workhrs avghrs                  // OLS regression
eststo:   mixed jobsatis workhrs avghrs || country:      // RE regression
 qui matrix foo = e(N_g)          // Number of individuals
 qui estadd scalar nc  = foo[1,1] // Number of individuals

 // Prepare data for meta-regression
preserve  // Generate country-level data set of average working hours
 egen pickone = tag(country)
 keep if pickone
 keep country avghrs 
 tempfile temp
 save `temp', replace
restore

 // Average job satisfaction per country, controlling for individual working hours
statsby _b[_cons] _se[_cons] e(N), clear by(country): regress jobsatis workhrs
 // Merge with average working hours
merge 1:1 country using `temp'

eststo: regress _stat_1  avghrs                // OLS regression two-step
eststo: vwls _stat_1  avghrs, sd(_stat_2)      // FE meta-regression
eststo: metareg _stat_1  avghrs, wsse(_stat_2) // RE meta-regression

esttab, keep(main:) mtitles("OLS" "Multilevel" "OLS two-step" "FE meta-regression" "RE meta-regression") b(3) se(3) /// coeflabel(workhrs "Working hours" /// avghrs "Average working hours" /// _cons "Intercept") /// stats(nc N, labels("No. countries") fmt(%12.0gc %12.0gc)) varwidth(25) modelwidth(20) eqlabels("", none)

Jul 27, 2017

Random graphs (105): Scatterplot

// Open ISSP data
use C_ALPHAN SEX V51 WEIGHT using ZA4350_v2-0-0.dta, clear

// Fix country variable
replace C_ALPHAN = "BE" if C_ALPHAN == "BE-FLA"
replace C_ALPHAN = "DE" if C_ALPHAN == "DE-E"
replace C_ALPHAN = "DE" if C_ALPHAN == "DE-W"
replace C_ALPHAN = "UK" if C_ALPHAN == "GB-GBN"

// Recode job satisfaction
recode V51 (7 = 0 "Completely dissatisfied") ///
           (6 = 1 "Very dissatisfied") ///
           (5 = 2 "Fairly dissatisfied") ///
           (4 = 3 "Neither satisfied nor dissatisfied") ///
           (3 = 4 "Fairly satisfied") ///
           (2 = 5 "Very satisfied") ///
           (1 = 6 "Completely satisfied"), gen(jobsat)
label var jobsat "Job satisfaction"

// Recode sex
gen female = (SEX == 2) if !missing(SEX)
label define female 0 "Male" 1 "Female"
label val female female
label var female "Sex"
drop if missing(female)

// Get rid of old variables
drop SEX V51

// Collapse and reshape data
collapse jobsat [pw = WEIGHT], by(C_ALPHAN female)
reshape wide jobsat, i(C_ALPHAN) j(female)

label var jobsat0 "Job satisfaction: men"
label var jobsat1 "Job satisfaction: women"

// Plot
twoway (scatter jobsat0 jobsat1 if jobsat0 > jobsat1, mlabel(C_ALPHAN) mlabpos(9)) ///
       (scatter jobsat0 jobsat1 if jobsat0 < jobsat1, mlabel(C_ALPHAN) mlabpos(6)) ///
       (function y = x, range(3.5 5.1))  ///
     , xlabel(3.5 (.5) 5.0, format(%6.2f)) ///
       ylabel(3.5 (.5) 5.0, format(%6.2f)) ///
       ytitle("Job satisfaction: men") ///
       xtitle("Job satisfaction: women") ///
       title("Cross-national variation in the gender gap in job satisfaction", span) ///
       note(" " "{it:Source:} International Social Survey Program (ISSP) 2005, doi:10.4232/1.11648", span) ///
       legend(off) name(figure1, replace)

Sep 10, 2016

Latex tables using -esttab-

// Table 1
eststo clear
bysort male country: eststo: estpost summarize hwhrs phwhrs gap ///
                                               workhours pworkhours ///
                                               genderroles femaleemployment ///
                                               married higherincome phigherincome ///
                                               age preschool schoolage ///
                                               retired pretired, listwise

esttab using test.tex, main(mean) aux(sd) label nodepvar nostar nonote nonumbers ///
                       b(%9.2f) varwidth(35) compress booktabs ///
                       title("Descriptive statistics: Means and standard deviations by gender and country") ///
                       mgroups("Women" "Men", pattern(1 0 0 1 0 0) ///
                       prefix(\multicolumn{@span}{c}{) suffix(})   ///
                       span erepeat(\cmidrule(lr){@span})) replace 
 
// Table 2
eststo clear
levelsof country, local(country)
foreach i of local country {
  capture drop touse
  mark touse
  markout touse   hwhrs workhours pworkhours phwhrs ///
                  genderroles femaleemployment ///
                  i.relativeincome pretired retired ///
                  age preschool schoolage married

  eststo: regress hwhrs workhours pworkhours phwhrs ///
          if female == 1 & country == `i' & touse
  eststo: regress hwhrs workhours pworkhours phwhrs ///
                  genderroles femaleemployment ///
                  i.relativeincome pretired retired ///
                  age preschool schoolage married ///
                  if female == 1 & country == `i' & touse
}

esttab using test.tex, se ar2 label varwidth(35) b(%9.2f) compress nodepvars order(_cons) booktabs ///
        mtitles("Germany" "Germany" "USA" "USA" "Finland" "Finland") ///
        title("Determinants of weekly housework hours of women in West Germany, USA, and Finland. OLS coefficients") ///
        append

Apr 30, 2016

Random graphs (79): Means with confidence intervals

use ZA5900_v3-0-0.dta, replace

renvars, lower // Switch variable names to lower case

// Fix country variable
generate cntry = c_alphan
replace  cntry = "GB" if cntry == "GB-GBN"
replace  cntry = "DE" if cntry == "DE-E"   | cntry == "DE-W"
replace  cntry = "BE" if cntry == "BE-BRU" | cntry == "BE-WAL" | cntry == "BE-FLA" 

// Generate country name variable
kountry cntry, from(iso2c)
encode NAMES_STD, gen(country)
drop NAMES_STD

// Happiness variable
recode v55 (1 = 6) (2 = 5) (3 = 4) (4 = 3) (5 = 2) (6 = 1) (7 = 0) (0 8 9 = .), gen(lsat)

label define lsat 0 "Completely unhappy" ///
                  1 "Very unhappy" ///
                  2 "Fairly unhappy" ///
                  3 "Neither happy nor unhappy" ///
                  4 "Fairly happy" ///
                  5 "Very happy" ///
                  6 "Completely happy"
label val lsat lsat
label var lsat "Happiness"

// Plot means by country
preserve
statsby mean_ = _b[_cons] ///
        loci  = (_b[_cons] - 1.96 * _se[_cons]) ///
        hici  = (_b[_cons] + 1.96 * _se[_cons]) ///
      , by(country) total clear: ///
        regress lsat

replace country = 1000 if country == .
label define country 1000 "{bf: Total}", modify

egen order_ = rank(mean_), unique
labmask order_, value(country) decode

twoway (rcap mean_ mean_ order_, horizontal) ///
       (rspike loci hici order_, horizontal) ///
      , legend(off) ylabel(1/41, valuelabels ang(h) labsize(*.8)) ///
        xlabel(3.5 (.5) 5.0, grid format(%6.1f)) name(lsat, replace)  ///
        xmtick(3.5 (.25) 5.0, grid) ///
        ytitle("") xtitle("Average happiness") xscale(alt) ysize(8) ///
        note(" " ///
             "{it:Note:} Happiness ranges from 0 ('Completely unhappy') to 6 ('Completely happy')" ///
             "{it:Source:} ISSP 2012, doi:10.4232/1.12339" , span size(*.8))
restore

Mar 21, 2016

Dropping one group at a time


// Interaction plot excluding one country at a time
foreach n of numlist 1/35 {  /// Countries are numbered from 1 to 35

  preserve
  qui drop if country == `n'      // Drop one country
  local naam: label country `n'   // Save name in a local
  *di "`naam'"

  qui mixed happiness c.workfamconf##c.gdppc || country: workfamconf, cov(uns)
  predict u1 u0, reffect

  capture drop pickone
  egen pickone = tag(country)
  qui keep if pickone

  gen wfceffect = u1 + _b[workfamconf] + _b[c.workfamconf#c.gdppc] * gdppc

  qui sum gdppc // get standard deviation
  local gdpmin2sd = r(mean) - 2*r(sd)
  local gdpminsd  = r(mean) -   r(sd)
  local gdpmean   = r(mean)
  local gdpplusd  = r(mean) +   r(sd)
  local gdpplu2sd = r(mean) + 2*r(sd)

  twoway (scatter wfceffect gdp, mlabel(country) mlabpos(0) msymbol(none) mlabsize(*.8)) ///
         (function y = _b[workfamconf] + _b[c.workfamconf#c.gdppc] * x, range(gdppc)) ///
        , ytitle("WFC coefficient", size(*.6)) ///
          xlabel(`gdpmin2sd' "-2 SD" `gdpminsd' "-1 SD" ///
                 `gdpmean' `"Avg."' ///
                 `gdpplusd' "+1 SD" `gdpplu2sd' "+2 SD", labsize(*.8)) ///
          title("Excluding `naam'") ///
          legend(off) ///
          name(figurewo`n', replace) xsize(3) ysize(2.5) nodraw
  restore
}

graph combine figurewo1  figurewo2 ///
              figurewo3  figurewo4 ///
              figurewo5  figurewo6 ///
              figurewo7  figurewo8 ///
              figurewo9  figurewo10 ///
              figurewo11 figurewo12 ///
              figurewo13 figurewo14 ///
              figurewo15 figurewo16 , col(4) row(4) xsize(12) ysize(10)
// And so on ...

Oct 6, 2015

Random graphs (54): Cross-level interactions

use deleteme.dta

// Cross-level interaction model
qui mixed lsat c.wfc##c.gdp || country: wfc , cov(uns)
estimates store cross_lvl  
qui estadd scalar dev = -2*e(ll) // Deviance
qui matrix foo = e(N_g)          // Number of level 2 units
qui estadd scalar nc  = foo[1,1] // Number of level 2 units
qui estadd scalar v2  = exp(2*[lns1_1_1]_b[_cons])     // Slope variance
qui estadd scalar v1  = exp(2*[lns1_1_2]_b[_cons])     // Intercept variance
qui estadd scalar cov = tanh([atr1_1_1_2]_b[_cons]) * /// Slope-intercept covariance
                        exp([lns1_1_1]_b[_cons])  * ///
                        exp([lns1_1_2]_b[_cons])
qui estadd scalar v_e = exp(2*[lnsig_e]_b[_cons])     // Residual variance

// Create table esttab cross_lvl /// , se /// stats(v1 v2 v_e cov dev nc N, /// Add variance components to table labels("Var(Intercept)" /// "Var(Slope)" /// "Var(Residual)" /// "Cov(Int., Slope)" /// "Deviance" /// "No. clusters" /// "No. individuals")) /// coeflabel(wfc "Work-family conflict" /// gdp "GDP" /// c.wfc#c.gdp "Work-family conflict X GDP" /// _cons "Intercept") /// mtitles("Cross-level interaction") /// nonumbers varwidth(28) modelwidth(24) /// keep(lsat:) // Drop variance components in weird shapes // Interaction plot (A) preserve estimates restore cross_lvl qui sum wfc // get standard deviation and mean local wfcminsd = r(mean) - r(sd) local wfcmean = r(mean) local wfcplusd = r(mean) + r(sd) qui sum gdp // get standard deviation local gdpmin2sd = r(mean) - 2*r(sd) local gdpminsd = r(mean) - r(sd) local gdpmean = r(mean) local gdpplusd = r(mean) + r(sd) local gdpplu2sd = r(mean) + 2*r(sd) margins, at(gdp = (`gdpmin2sd' `gdpminsd' `gdpmean' `gdpplusd' `gdpplu2sd') /// wfc = (`wfcminsd' `wfcmean' `wfcplusd')) vsquish marginsplot, x(gdp) noci /// xlabel(`gdpmin2sd' "-2 SD" /// `gdpminsd' "-1 SD" /// `gdpmean' `""Average" "GDP""' /// `gdpplusd' "+1 SD" /// `gdpplu2sd' "+2 SD") /// xtitle("") /// ylabel(, format(%6.1f)) /// ytitle("Predicted happiness") /// plotopts(msymbol(none)) /// // Turn off markers plot1opts(lpattern(longdash)) /// // Define line types here plot2opts(lpattern(solid)) /// plot3opts(lpattern(shortdash)) /// legend(subtitle("Work{c 150}family conflict" , size(small)) /// order(1 "- 1 SD" 2 "Mean" 3 "+ 1 SD") size(small) /// pos(11) ring(0)) /// title("(A) Interaction plot") /// name(xlvl_plot1, replace) restore // Interaction plot (B) preserve estimates restore cross_lvl predict u1 u0, reffect capture drop pickone egen pickone = tag(country) keep if pickone gen wfceffect = u1 + _b[wfc] + _b[c.wfc#c.gdp] * gdp qui sum gdp // get standard deviation local gdpmin2sd = r(mean) - 2*r(sd) local gdpminsd = r(mean) - r(sd) local gdpmean = r(mean) local gdpplusd = r(mean) + r(sd) local gdpplu2sd = r(mean) + 2*r(sd) twoway (scatter wfceffect gdp, mlabel(country) mlabpos(0) msymbol(none)) /// (function y = _b[wfc] + _b[c.wfc#c.gdp] * x, range(gdp)) /// , ytitle("Work{c 150}family conflict coefficient") /// xlabel(`gdpmin2sd' "-2 SD" `gdpminsd' "-1 SD" /// `gdpmean' `""Average" "GDP""' /// `gdpplusd' "+1 SD" `gdpplu2sd' "+2 SD") /// title("(B) Interaction plot") /// legend(order(2 "Work{c 150}family conflict coefficient by GDP") /// pos(7) ring(0) size(small)) /// name(xlvl_plot2, replace) restore // Combine graphs graph combine xlvl_plot1 xlvl_plot2, row(1) ysize(3) xsize(5.5) altshrink

Oct 15, 2014

Random graphs (33): Regression parameters

 
use V4 V56 SEX using "ZA5900_v2-0-0.dta", replace // ISSP 2012 data

renvars, lower // Switch variable names to lower case

kountry v4, from(iso3n) to(iso2c)  // Generate country abbreviation variable
replace _ISO2C_ = "RU" if v4 == 643
encode _ISO2C_, gen(country)

drop if cntry == "ZA" // v56 missing in ZA

// Prepare variables
recode sex (9 = .)
recode v56 (0 8 9 = .), gen(jobsat_rev)
generate jobsat = 7 - jobsat_rev
label define jobsat 6 "Completely satisfied" ///
                    3 "Neither satisfied nor dissatisfied" ///
                    0 "Completely dissatisfied"
label value jobsat jobsat

preserve

// Save parameters
statsby gendergap = _b[sex]  ///
        loci      = (_b[sex] - 1.96 * _se[sex]) ///
        hici      = (_b[sex] + 1.96 * _se[sex]) ///  
  , by(country) clear total: ///
  regress jobsat sex

replace country = 1000 if country == .  // Label parameter from total sample
label define country 1000 "{bf: Total}", modify // Label parameter from total sample

egen order_ = rank(-gendergap), unique
labmask order_, value(country) decode

twoway (dot gendergap order_, msize(vsmall)) ///
       (rcap loci hici order_) ///
     , legend(off) xlabel(1/37, valuelabels ang(v)) ///
       yline(0) note("{it:Source:} ISSP 2012 (Family and Changing Gender Roles IV), own calculations", span) ///
       ylabel(,format(%6.1f)) name(gendergap, replace) ///
       xtitle(" ") ytitle("Gender gap in job satisfaction")

restore

Jul 16, 2014

Random graphs (28): Plotting categorical variables

foreach x of varlist V39 V40 V41 {

    // Recode each variable:
  recode `x' (1/5 = 2 "Valid answer") ///
             ( .c = 1 "Can't choose") ///
             ( .n = 0 "No answer") ///
    , gen(`x'_mis)
  label var `x'_mis "Recode of `x'"
  
    // Plot each variable:
  catplot `x'_mis, over(C_ALPHAN, label(ang(v)))
                   stack asyvars perc(C_ALPHAN) ///
                   legend(pos(1) row(1)) recast(bar) ///
     ytitle("Percentage") b1title("") ///
     title("Recode of `x'") ///
     name(`x'_mis, replace)
}

grc1leg V39_mis V40_mis V41_mis, col(1) name(combined, replace)
graph display combined, ysize(11) xsize(7)

May 28, 2014

Calculate coefficient alpha by country

use "ZA5900_v1-0-0.dta", replace

renvars, lower // Switch variable names to lower case

kountry v4, from(iso3n) to(iso2c)  // Generate country abbreviation variable
encode _ISO2C_, gen(country)

fre v51-v54 // Work-family conflict items

// Factor analysis yields one-dimensional solution:
factor v51-v54, pcf


// Calculate Cronbach's alpha for each country of the sample:

preserve

statsby alpha_ = r(alpha) ///
      , by(country) clear total: /// -total- adds row for total sample
    alpha v51-v54

replace country = 25 if country == .  // Label row for total sample
label define country 25 "All", modify // Label row for total sample    
    
sort alpha_         // Make list 
list, sep(0)

  // Create graph
egen order_ = rank(-alpha_), unique
labmask order_, value(country) decode

twoway (dot alpha_ order_) ///
       , yline(.70) ///
      xlab(1/25, valuelabels ang(v)) xtitle("Country") ///
   ylabel(, format(%6.2f)) ytitle("Cronbach's alpha of work{c 150}family conflict scale") ///
   note("{it: Note:} Horizontal line denotes conventional cut-off value for Cronbach's alpha", span)

restore

Oct 8, 2013

Random graphs (16): Plots with confidence intervals


preserve

reg srh i.country [pweight = weight]

predict means, xb
predict semeans, stdp

gen loci = means - 1.96 * semeans
gen hici = means + 1.96 * semeans

keep if pickone
 
egen order_ = rank(-means), unique
labmask order_, value(country) decode

twoway (dot means order_) (rcap loci hici order_) ///
        , legend(off) xlab(1/29, valuelabels ang(v)) ///
         ylabel(, format(%6.1f)) ///
         ytitle("Self-rated health") ///
         xtitle("") ///
         note(`"Note: SRH ranges from 0 ("poor") to 4 ("excellent")"', span)

restore
preserve

logit srh_bin i.country [pweight = weight]

predict lr_index, xb
predict se_index, stdp
generate p_hat = exp(lr_index)/(1+exp(lr_index)) // Predicted probabilities
 // (following http://www.stata.com/support/faqs/...)
gen lb = lr_index - invnormal(0.975)*se_index
gen ub = lr_index + invnormal(0.975)*se_index
gen plb = exp(lb)/(1+exp(lb))
gen pub = exp(ub)/(1+exp(ub))

replace p_hat = p_hat * 100
replace plb = plb * 100
replace pub = pub * 100
keep if pickone
 
egen order_ = rank(p_hat), unique
labmask order_, value(country) decode

twoway (dot p_hat order_) (rcap plb pub order_) ///
       , legend(off) xlab(1/29, valuelabels ang(v)) ///
         ylabel(, format(%6.0f)) ///
         ytitle("% Poor health") xtitle("")

Oct 5, 2012

Random graphs (4): Plotting intercept and slope variation


use V3 V51 ISCO88 using "C:\Users\User\work\data sets\issp - work orientations\work orientations iii (2005)\ZA4350_F1.dta", clear

// Generate variables
gen jobsatisf = 7 - V51
iskoisei isei, isko(ISCO88)
drop V51 ISCO88
preserve

// Calculating intercept and slope variation using OLS statsby inter = _b[_cons] /// slope = _b[isei] /// , by(V3) /// saving(ols, replace): /// regress jobsatisf isei merge m:1 V3 using ols drop _merge // Visualizing intercept and slope variation gen yhat_ols = inter + slope*isei separate jobsatisf, by(V3) separate yhat_ols, by(V3) twoway (line yhat_ols1-yhat_ols43 isei, sort(V3 isei)) /// (lfit jobsatisf isei, clwidth(vvthick) clcolor(black)) /// , legend(off) ytitle("Job satisfaction") xtitle("ISEI") /// xlabel(16 25 50 75 90) ylabel(,format(%6.1f)) /// caption("{it:Source:} ISSP 2005 (Work Orientations III), own calculations", span) /// name(one, replace) restore
// Calculating intercept and slope variation using a random effects model center isei, inplace mixed jobsatisf isei || V3: isei, var predict u1 u0, reffects // Visualizing intercept and slope variation gen predRandomSlope = (_b[_cons] + u0) + ((_b[isei] + u1) * isei) twoway (line predRandomSlope isei, connect(ascending) sort(V3 isei)), /// ytitle("Job satisfaction") /// xtitle("ISEI (centered)") /// xlabel(-25 0 25 50) /// ylabel(,format(%6.1f)) /// caption("{it:Source:} ISSP 2005 (Work Orientations III), own calculations", span) /// name(two, replace)