Showing posts with label statsby. Show all posts
Showing posts with label statsby. Show all posts

Nov 3, 2017

Random graphs (115): Bar graphs

// Data
use ESS7e02_1.dta, clear

// Drinking variable
recode alcfreq (7 = 0 "Never") (6 = 1 "Less than once a month") ///
               (5 = 2 "Once a month") (4 = 3 "2{c 150}3 times a month") ///
               (3 = 4 "Once a week") (2 = 5 "Several times a week") ///
               (1 = 6 "Every day") (77 88 99 = .), gen(alcohol)
label var alcohol "Alcohol consumption"

// Dichotomize alcohol variable
generate drinking = inlist(alcohol, 5, 6) if !missing(alcohol)      

// Country name variable
kountry cntry, from(iso2c) marker
rename NAMES_STD country
  
// Education
recode eisced (1 2   = 0 "Lower") ///
              (3 4 5 = 1 "Medium") ///
     (6 7   = 2 "High") ///
     (55/99 = .), gen(education)
label var education "Education"

// Alcohol consumption by country
histogram alcohol, percent disc horizontal ///
                   by(country, title("{bf:A} Frequency of drinking alcohohl", ///
                         justification(left) bexpand span) ///
                               note("")) ///
                   ylabel(0(1)6, val) ytitle("") ///
                   ysize(8) name(figure1, replace)

// Alcohol consumption by education by country
  // Collect predicted probabilities
capture program drop my_logit
program define my_logit, eclass
    syntax[if]
    marksample touse
    logit drinking if `touse'
    margins if `touse', post
    exit
end

statsby point = _b[_cons] se = _se[_cons], by(country education) clear: my_logit

 // Calculate stuff
replace point = point * 100
replace se = se * 100

gen lb = point - 1.96 * se
gen ub = point + 1.96 * se

  // Plot
twoway (bar point point education) ///
       (rspike lb ub education), ///
    by(country, legend(off) ///
                   title("{bf:B} Drinking by educational attainment", ///
                         justification(left) bexpand span) ///
                   note("")) ///
       xlabel(0 1 2, val ang(v)) ylabel(0 (10) 50) ///
       ytitle("% drinking more than once a week") ///
    ysize(8) ///
    name(figure2, replace)

graph combine figure1 figure2, col(2) ///
                               note(" " "{it:Source:} European Social Survey 2014", ///
                                    span justification(right) bexpand size(*.8))

Oct 11, 2017

Random graphs (114): Line plot and choropleth

use ESS1-7e01, clear

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

// Create No contract variable
gen nocontract = (wrkctra == 3) if !missing(wrkctra)

// Calculate per year and country
preserve
statsby cont = _b[_cons] contse = _se[_cons], by(country essround) clear: regress nocontract

replace cont = cont * 100             // Convert proportion into precentage
generate  lb = cont - (contse * 100)
generate  ub = cont + (contse * 100)

label define essround 1 "2002" 2 "2004" 3 "2006" 4 "2008" 5 "2010" 6 "2012" 7 "2014", modify

sort essround country
twoway (rarea lb ub essround) ///
       (connected cont essround), ///+
        by(country, legend(off) note(" " "{it:Source:} ESS 2002-2014", span) ///
        title("{bf:A}", justification(left) bexpand span)) ///
        xtitle("") xlabel(1/7, val ang(45)) ytitle("% no contract") ///
        xsize(6) ysize(6) ///
        name(figurea, replace) 
restore
  
// Calculate average % no contracts per country
collapse nocontract, by(cntry)
replace nocontract = nocontract * 100
format nocontract %6.1f
saveold cont, replace
  
// Read in map data
  // Source: shapefile from http://www.naturalearthdata.com/downloads/10m-cultural-vectors/
shp2dta using "maps\ne_10m_admin_0_countries", database(database)  coordinates(coordinates) genid(id) replace

  // Restrict coordinates to Europe
  // Source: https://en.wikipedia.org/wiki/Extreme_points_of_Europe
use coordinates, clear
replace _Y = . if _Y < 36
replace _Y = . if _Y > 71 & !missing(_Y)
replace _X = . if _X < -28 
replace _X = . if _X > 33 & !missing(_X)
saveold europecoordinates, replace

  // Create data set with Europe internal borders
clonevar id = _ID
merge m:1 id using database, nogenerate
keep if CONTINENT == "Europe"
saveold europe, replace

  // Merge map data with set with data to be plotted
use ISO_A2 NAME id using database, clear
rename ISO_A2 cntry
replace cntry = "FR" if NAME == "France" // Somehow not correct in map
replace cntry = "NO" if NAME == "Norway" // Somehow not correct in map
drop if cntry == "-99"
merge 1:1 cntry using cont, keep(matched) nogenerate

spmap nocontract using europecoordinates, id(id) xsize(6) ysize(6) ///
                                     polygon(data(europe)) legstyle(2) clnumber(9) ///
                                     legend(position (9) ring(0)) fcolor(Oranges) ///
                                     legorder(hilo) ocolor(none ..) ///
                                     title("{bf:B}", justification(left) bexpand span) ///
                                     legtitle("{bf:% no contract, 2002-2014 averages}") legjunction({c 150}) ///
                                     note(" " "{it:Source:} ESS 2002-2014", span) name(figureb, replace)
          
graph combine figurea figureb, row(1) xsize(12)

Sep 7, 2017

Random graphs (112): Line plot

clear 
// Open Eurostat data
unzipfile "macrodata\lfsi_pt_a.zip"
insheet using lfsi_pt_a_1_Data.csv

// Prepare variables
replace value = "." if value == ":"
destring value, gen(fixedterm)
rename time year
replace geo = "France" if geo == "France (metropolitan)"
kountry geo, from(other) stuck
rename _ISO3N_ country
kountry country, from(iso3n) to(iso2c)
rename _ISO2C_ cntry

// Select data and save
keep if year >= 2004
keep fixedterm geo year cntry
save lfs_fixedterm, replace

// Open ESS data
use essround agea mnact wrkctra pspwght cntry using ESS1-7e01, clear

// Select data
keep if essround >= 2
keep if inrange(agea, 20, 64)
keep if mnact == 1

// Prepare variables
generate ess_fixedterm = (wrkctra == 2)
replace  ess_fixedterm = (ess_fixedterm * 100)
generate year = 2004 if essround == 2
replace  year = 2006 if essround == 3
replace  year = 2008 if essround == 4
replace  year = 2010 if essround == 5
replace  year = 2012 if essround == 6
replace  year = 2014 if essround == 7

// Point estimates and standard errors
statsby ess_fixedterm = _b[_cons] se = _se[_cons], clear by(cntry year): regress ess_fixedterm

// Merge Eurostat data with ESS data
merge 1:1 cntry year using lfs_fixedterm

// Select countries 
drop if inlist(cntry, "RU", "IL", "UA", "LV", "MK", "MT", "RO")

// Generate country name variable
kountry cntry, from(iso2c) 
ren NAMES_STD country

// Calculate confidence intervals
generate lb = ess_fixedterm - 1.96 * se
generate ub = ess_fixedterm + 1.96 * se

// Plot figure
sort year
twoway (rarea ub lb year, lcolor(white)) ///
       (connected ess_fixedterm year) ///
       (line fixedterm year), by(country, note("")) ///
        xtitle("") ytitle("Percentage of total employed (20{c 150}64 y)" "on temporary contract") ///
        legend(order(2 "ESS" 1 "95% CI" 3 "Eurostat") row(1)) xlabel(2004 (2) 2014)


May 25, 2017

Random graphs (96): Categorical variables

use S003A S002 X001 C041 C039 C038 C037 if inlist(S002, 4, 5) ///
    using WVS_Longitudinal_1981-2014_stata_v_2014_11_25.dta, clear

// Declare missing values
mvdecode C041 C039 C038 C037, mv(-5 -4 -3 -2 -1)

// Factor analysis
factor C041 C039 C038 C037, pcf
alpha C041 C039 C038 C037, item
local alph = round(`r(alpha)', .01)

// Prepare variables
scores nonworkethic = mean(C041 C039 C038 C037), nv(3) 
generate workethic = 5 - nonworkethic 
gen male = (X001 == 1) if X001 != -2
drop nonworkethic X001
// Create descriptive plot foreach var of varlist C041 C039 C038 C037 { recode `var' (1 = 4 "Strongly agree") /// (2 = 3 "Agree") /// (3 = 2 "Neither agree nor disagree") /// (4 = 1 "Disagree") /// (5 = 0 "Strongly disagree"), gen(`var'_rec) numlabel `var'_rec, add mask("# ") twoway histogram `var'_rec, discrete horizontal yla(0/4, valuelabel) percent /// title("`: variable label `var''") /// ytitle("") /// name(`var', replace) nodraw drop `var'_rec } graph combine C041 C039 C038 C037, col(2) row(2) altshrink title("Work ethic is measured as the average of four items:") /// caption("In a PCA, all items load on one dimension; explained variance = 49%, Cronbach's alpha = `alph'", span) note("{it:Source:} WVS 1999-2009, pooled", span) name(figure1, replace) drop C041 C039 C038 C037
// Calculate country differences preserve statsby mean_ = _b[_cons] /// loci = (_b[_cons] - 1.96 * _se[_cons]) /// hici = (_b[_cons] + 1.96 * _se[_cons]) /// , by(S003A) clear: /// regress workethic // Sort coefficients by size egen order_ = rank(mean_), unique labmask order_, value(S003A) decode // Plot twoway (rcap mean_ mean_ order_, horizontal) /// (rspike loci hici order_, horizontal) /// , legend(off) ylabel(1/63, valuelabels ang(h) labsize(*.8)) /// xlabel(0 (1) 4, grid format(%6.1f)) name(all, replace) /// xmtick(0 (.5) 4) /// ytitle("") xtitle("Work ethic across countries") /// title("{bf:A}", justification(left) bexpand span) /// xscale(alt) ysize(10) nodraw restore // Country differences--men only preserve statsby mean_ = _b[_cons] /// loci = (_b[_cons] - 1.96 * _se[_cons]) /// hici = (_b[_cons] + 1.96 * _se[_cons]) /// , by(S003A) clear: /// regress workethic if male == 1 // Sort coefficients by size egen order_ = rank(mean_), unique labmask order_, value(S003A) decode // Plot twoway (rcap mean_ mean_ order_, horizontal) /// (rspike loci hici order_, horizontal) /// , legend(off) ylabel(1/63, valuelabels ang(h) labsize(*.8)) /// xlabel(0 (1) 4, grid format(%6.1f)) name(men, replace) /// xmtick(0 (.5) 4) /// ytitle("") xtitle("Men's work ethic across countries") /// title("{bf:B}", justification(left) bexpand span) /// xscale(alt) ysize(10) nodraw restore // Calculate gender gap preserve statsby mean_ = _b[male] /// loci = (_b[male] - 1.96 * _se[male]) /// hici = (_b[male] + 1.96 * _se[male]) /// , by(S003A) clear: /// regress workethic male // Sort coefficients by size egen order_ = rank(mean_), unique labmask order_, value(S003A) decode // Plot twoway (rcap mean_ mean_ order_, horizontal) /// (rspike loci hici order_, horizontal) /// , legend(off) ylabel(1/63, valuelabels ang(h) labsize(*.8)) /// xlabel(-.25 (.25) .5, grid format(%6.2f)) name(gendergap, replace) /// xmtick(-.25 (.1) .5) /// text(63 .5 "Men" "higher", place(sw)) /// text( 1 -.25 "Women" "higher", place(ne)) /// ytitle("") xtitle("Gender gap in work ethic") /// title("{bf:C}", justification(left) bexpand span) /// xscale(alt) ysize(10) nodraw restore graph combine all men gendergap, note(" " "{it:Source:} WVS 1999-2009, pooled", span) col(3) ysize(12) xsize(18) altshrink /// title("Work ethic in cross-national comparison", span) name(figure2, replace)

Feb 26, 2017

Chapter 2 of Singer and Willett's (2003) book on longitudinal data analysis

There is a different take on the chapter here, but I like mine better.
// Open data set
use http://www.ats.ucla.edu/stat/stata/examples/alda/data/tolerance, clear

// Figure 2.1
list, sep(0) noobs
reshape long tol, i(id) j(age)
list if inlist(id, 9, 45, 1653), sepby(id) noobs

// Table 2.1
reshape wide
quietly estpost cor tol*, matrix listwise
esttab, unstack not noobs compress nostar b(%6.2f)

// Figure 2.2
reshape long
twoway (scatter tol age), by(id) ytitle(Tolerance) xtitle(Age) name(Figure22, replace)

// Figure 2.3
twoway (scatter tol age) ///
       (lowess tol age) ///
      , by(id, note("Graphs by id, lowess curves") legend(off)) ///
        ytitle(Tolerance) xtitle(Age) name(Figure23, replace)

// Table 2.2
preserve
tempfile table22
generate time = age - 11
statsby initial    = _b[_cons]  ///
        initial_se = _se[_cons] ///
        change       = _b[time] ///
        change_se    = _se[time] ///
        residual   = (e(rmse)^2) ///
        explained  = e(r2) ///
      , by(id) saving(`table22', replace): regress tol time
drop time
reshape wide  

merge 1:1 id using `table22', nogenerate
format    initial initial_se change change_se residual explained      exposure %6.2f
keep   id initial initial_se change change_se residual explained male exposure
order  id initial initial_se change change_se residual explained male exposure
list, sep(0) noobs abbrev(15)

tempfile figure28
save `figure28', replace

// Figure 2.4
stem initial, round(.01)
stem change, round(.01)
stem residual, round(.01)
stem explained, round(.01)
restore

// Figure 2.5
twoway (scatter tol age) ///
       (lfit tol age) ///
      , by(id, note("Graphs by id, OLS curves") legend(off)) ///
        ytitle(Tolerance) xtitle(Age) name(Figure25, replace)
   
// Figure 2.6
xtset id age
xtline tol, overlay t(age) i(id) legend(off) ///
            ytitle(Tolerance) ylabel(1 (1) 4) ///
            addplot(lowess tol age, lwidth(thick) lpattern(solid)) ///
            xtitle(Age) title("Observed data and lowess smoother") ///
            xsize(3) name(Figure26A, replace) nodraw
quietly regress tol i.id##c.age
predict tolhat
xtline tolhat, overlay t(age) i(id) legend(off) ///
               ytitle(Tolerance) ylabel(1 (1) 4) ///
               addplot(lfit tol age, lwidth(thick) lpattern(solid)) ///
               xtitle(Age) title("OLS trajectories") ///
               xsize(3) name(Figure26B, replace) nodraw
graph combine Figure26A Figure26B, col(2) name(Figure26, replace)

// Table 2.2
preserve
use `table22', clear
tabstat initial change, stat(mean sd) format(%6.2f)
cor initial change
restore

// Figure 2.7
quietly sum exposure, detail
generate highexposure = (exposure >= r(p50))
generate  lowexposure = (exposure  < r(p50))
generate  female      = !male
label var male         "Males"
label var female       "Females"
label var lowexposure  "Low exposure"
label var highexposure "High exposure" 

foreach z of varlist female male lowexposure highexposure {
  capture drop tolhat
  quietly regress tol i.id##c.age if `z'
  predict tolhat if `z'
  xtline tolhat if `z', ///
         overlay t(age) i(id) legend(off) ///
         ytitle("Predicted tolerance") ylabel(1 (1) 4) ///
         addplot(lfit tol age if `z', lwidth(thick) lpattern(solid)) ///
         xtitle(Age) title(`: variable label `z'') ///
         xsize(3) ysize(2) name(Figure27_`z', replace) nodraw
}
graph combine Figure27_female Figure27_male Figure27_lowexposure Figure27_highexposure, col(2) name(Figure27, replace)

// Figure 2.8
use `figure28', clear

quietly correlate initial male 
local pmca = round(r(rho), .01)
quietly correlate initial exposure 
local pmcb = round(r(rho), .01)
quietly correlate change male 
local pmcc = round(r(rho), .01)
quietly correlate change exposure 
local pmcd = round(r(rho), .01)

label define male -1 " " 1 "Male" 0 "Female" 2 " ", modify
label val male male

twoway dot initial male, ///
       ytitle("Predicted intercept") ///
       xtitle("Gender") ///
       xlabel(-1 0 1 2, val) ///
       ysize(2) xsize(3) ///
       note("{it:r} = `pmca'") ///
       name(Figure28A, replace) nodraw
twoway scatter initial exposure, ///
       ytitle("Predicted intercept") ///
       xtitle("Exposure") ///
       ysize(2) xsize(3) ///
       note("{it:r} = `pmcb'") ///
       name(Figure28B, replace) nodraw
twoway dot  change  male, ///
       ytitle("Predicted change") ///
       xtitle("Gender") ///
       ysize(2) xsize(3) ///
       xlabel(-1 0 1 2, val) ///
       note("{it:r} = `pmcc'") ///
       name(Figure28C, replace) nodraw
twoway scatter change  exposure, ///
       ytitle("Predicted change") ///
       xtitle("Exposure") ///       
       ysize(2) xsize(3) ///
       note("{it:r} = `pmcd'") ///    
       name(Figure28D, replace) nodraw
graph combine Figure28A Figure28B Figure28C Figure28D, col(2) row(2) name(Figure28, replace)

Reference

Singer, Judith D., and John B. Willett. 2003. Applied Longitudinal Data Analysis. Modeling Change and Event Occurrence. Oxford University Press. doi: 10.1093/acprof:oso/9780195152968.001.0001

Oct 24, 2016

Random graphs (91): Regression coefficients

// ESS round 1
use ESS1e06_4.dta, clear

// Prepare variables
  // Country variable
  encode cntry, gen(country)

  // Trade union membership
  recode trummb (0 = 0 "Non-member") (1 = 1 "Trade union member") (. = .), generate(unionmember)
  label var unionmember "Trade union member"

  // Age
  generate age = agea if agea != 999
  label var age "Age"

  // Sex
  gen female = (gndr == 2) if gndr != 9
  label var female "Female sex"
  label define female 1 "Female" 0 "Male"
  label val female female

  // Happiness
  recode happy (77 88 99 = .)

  // Center age and sex
  center age female
  
// First set of models
  preserve   
  statsby mean_ = _b[unionmember] ///
          loci  = (_b[unionmember] - 1.96 * _se[unionmember]) ///
          hici  = (_b[unionmember] + 1.96 * _se[unionmember]) ///
        , by(country) clear: ///
          regress happy unionmember

  // Sort coefficients by size
  egen order_ = rank(mean_), unique
  labmask order_, value(country) decode

  // Plot
  twoway (rcap mean_ mean_ order_, horizontal) ///
         (rspike loci hici order_, horizontal) ///
        , legend(off) ylabel(1/20, valuelabels ang(h) labsize(*.8)) ///
          xlabel(-.5 (.5) 1.5, grid format(%6.1f)) name(unadjusted, replace)  ///
          xmtick(-.5 (.1) 1.5) ///
          ytitle("") xtitle("Happiness advantage of trade union membership" " ") ///
          xscale(alt) ysize(4)
restore  

// Second set of models
  preserve   
  statsby mean_ = _b[unionmember] ///
          loci  = (_b[unionmember] - 1.96 * _se[unionmember]) ///
          hici  = (_b[unionmember] + 1.96 * _se[unionmember]) ///
        , by(country) clear: ///
          regress happy unionmember c_female c_age

  // Sort coefficients by size
  egen order_ = rank(mean_), unique
  labmask order_, value(country) decode

  // Plot
  twoway (rcap mean_ mean_ order_, horizontal) ///
         (rspike loci hici order_, horizontal) ///
        , legend(off) ylabel(1/20, valuelabels ang(h) labsize(*.8)) ///
          xlabel(-.5 (.5) 1.5, grid format(%6.1f)) name(adjusted, replace)  ///
          xmtick(-.5 (.1) 1.5) ///
          ytitle("") xtitle("Happiness advantage of trade union membership" "(adjusted for age and sex)") ///
          xscale(alt) ysize(4)
  restore  
  
// Plot both underneath one another
graph combine unadjusted adjusted, row(2) ysize(8) xcommon name(combined, replace) ///
          note(" " ///
             "{it:Source:} ESS round 1, own calculations. {it:Note:} Error bars denote 95% confidence intervals." , span size(*.8))  

May 20, 2016

Merging the Demographic and Health Surveys in Stata

// Unzip files
clear
cd "C:\dhs"

local filelist : dir . files "*.zip"  // Create local with all filenames ending with ".zip"
di `filelist'

local first : word 1 of `filelist'      // Identify first file
di "`first'"

local total_ : word count `filelist' // Identify total number of files
di `total_'        

forvalues x = 1/`total_' {
    di `x'
    local y : word `x' of `filelist'
    unzipfile "`y'", replace
}

// Append all files
clear
cd "C:\dhs"
local directorylist : dir . dirs  "*ir*"  // Create local with all directory names that contain women's data

di `directorylist'

local firstdir : word 1 of `directorylist'      // Identify first directory
di "`firstdir'"

local total_ : word count `directorylist' // Identify total number of directories
di `total_'

local firstfile = strupper("`firstdir'")
local firstfile = subinstr("`firstfile'","DT","FL",.)
di "`firstfile'"

use caseid v000 v005 v007 v012 v106 v107 v155 v191 v201 v212 v525 v531 using "`firstdir'/`firstfile'", clear                    
capture decode v106, gen(v106s)
drop v106

save testfile, replace

forvalues x = 2/`total_' {
    local y : word `x' of `directorylist'
 local filename = strupper("`y'")
    local filename = subinstr("`filename'", "DT", "FL", .)
 use "`y'/`filename'", clear
 
 // Source: https://stackoverflow.com/questions/17056016/stata-how-to-keep-a-list-of-variables-given-some-of-them-may-not-exist
 local masterlist "caseid v000 v005 v007 v012 v106 v107 v155 v191 v201 v212 v525 v531"
    local keeplist = ""

    foreach i of local masterlist  {
    capture confirm variable `i'
        if !_rc {
            local keeplist "`keeplist' `i'"
        }
     }
    keep `keeplist'
 capture decode v106, gen(v106s)
    capture drop v106
 
 tempfile new
 save `new', replace
 use testfile, clear
 append using `new', force
 save testfile, replace
}

// Prepare variables
use testfile, clear

//Country and wave identifiers
replace v000 = "VN3" if v000 == "VNT"
generate cntry = substr(v000,1,2)
generate wavex  = substr(v000,3,1)
replace wavex = "1" if wavex == ""
encode wavex, gen(wave)
drop wavex

  // Fix unusual country abbreviations
replace cntry = "BI" if cntry == "BU"
replace cntry = "IN" if cntry == "IA"
replace cntry = "KZ" if cntry == "KK"
replace cntry = "BI" if cntry == "BU"
replace cntry = "MD" if cntry == "MB"
replace cntry = "NA" if cntry == "NM"
replace cntry = "DO" if cntry == "DR"

kountry cntry, from(iso2c)
encode NAMES_STD, gen(country)
drop NAMES_STD

// Select last wave
keep if wave == 6

// Prepare variables
  // Age at first intercourse
generate age1stintercourse = .
replace  age1stintercourse = v531 if inrange(v531, 1, 63)
replace  age1stintercourse = .a   if v525 == 0
replace  age1stintercourse = .b   if v525 == 95
replace  age1stintercourse = .c   if v525 == 97
replace  age1stintercourse = .d   if v525 == 98
replace  age1stintercourse = .e   if v525 == 99
label define age1stintercourse .a "Not had intercourse" ///
                               .b "95?" ///
                               .c "inconsistent" ///
                               .d "don't know" ///
                               .e "99?" 
label val age1stintercourse age1stintercourse
label var age1stintercourse "Age at first intercourse"

  // Age at first birth
rename v212 afb
label var afb "Age at first birth"

// Calculate correlation
preserve
statsby mean_ = _b[age1stintercourse] ///
        loci  = (_b[age1stintercourse] - 1.96 * _se[age1stintercourse]) ///
        hici  = (_b[age1stintercourse] + 1.96 * _se[age1stintercourse]) ///
      , by(country) total clear: ///
        regress afb age1stintercourse

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

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

// Plot
twoway (rcap mean_ mean_ order_, horizontal) ///
       (rspike loci hici order_, horizontal) ///
      , legend(off) ylabel(1/38, valuelabels ang(h) labsize(*.8)) ///
        xlabel(.7 (.1) 1.0, grid format(%6.1f)) name(ols, replace)  ///
        xmtick(.7 (.05) 1.0) ///
        ytitle("") xtitle("Association between" ///
                          "age at first intercourse" ///
                          "and age at first birth") xscale(alt) ysize(8) ///
        note(" " ///
             "{it:Source:} DHS VI, own calculations" , span size(*.8))
restore

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

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

Jun 20, 2014

Random graphs (26): Plot means by country

use cntry stflife using "ESS1e06.3_F1.dta", clear

encode cntry, gen(country)  // De-string country identifier

preserve

statsby mean_ = _b[_cons] ///
        loci  = (_b[_cons] - 1.96 * _se[_cons]) ///
        hici  = (_b[_cons] + 1.96 * _se[_cons]) ///
      , by(country) total clear: /// // -total- fits model for total sample
        regress stflife

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

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

twoway (dot mean_ order_, msize(vsmall)) ///
       (rcap loci hici order_) ///
     , legend(off) xlabel(1/23, valuelabels ang(v)) ///
       ylabel(,format(%6.1f)) name(lifesat, replace)  ///
       xtitle("") ytitle("Life satisfaction (avg.)")

restore

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 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)