Showing posts with label Latex. Show all posts
Showing posts with label Latex. Show all posts

Oct 18, 2019

Descriptive statistics table using -esttab-

// Open Allbus 1984-2016
use age iscd975 isei* sex using "ZA4586_v1-0-0.dta", clear

// Age
recode age (-32 = .)
label var age "Age"

// Education
recode iscd975 (-32 = .) ///
               (1 2 = 0 "Low") ///
               (3 4 = 1 "Medium") ///
               (5 = 2 "High"), gen(educ)
label var educ "Education"

// ISEI
generate isei = isei88  if inrange(isei88, 16, 90)
replace  isei = isei08  if missing(isei) & inrange(isei08, 16, 90)
replace  isei = isei68  if missing(isei) & inrange(isei68, 16, 90)
replace  isei = isei88a if missing(isei) & inrange(isei88a, 16, 90)
replace  isei = isei08a if missing(isei) & inrange(isei08a, 16, 90)
replace  isei = isei68a if missing(isei) & inrange(isei68a, 16, 90)
label var isei "ISEI" 

// Sex
recode sex (1 = 0 "Male") (2 = 1 "Female"), gen(female)
label var female "Sex"

// Listwise deletion
capture drop touse
mark touse
markout touse age educ sex isei

// Create dummies of categorical variables for descriptives table
foreach x of varlist educ female {               // Plug in categorical variables here
  qui tab `x', gen(`x'x)                         // Create dummy variables
  foreach var of varlist `x'x* {
   local lab `: var label `var''
   *di "`lab'"                                   // Display label
   *di strpos("`lab'", "==") 
   local i = strpos("`lab'", "==") + 2
   local lab `: di substr("`lab'",  `i', .)'
   label var `var' "\dumm `lab'"                // Add \dumm to label
  }
}

// Add this to Latex code to indent dummy variables
// % Indent for tables
// \newcommand*{\dumm}{\hspace*{0.5cm}}%

// Calculate descriptives and save them internally
eststo clear
estpost tabstat isei educx* age femalex* if touse, by(female) ///
                                                   statistics(mean sd min max) ///
                                                   columns(statistics)

// Format number of cases for table caption
local n: display %9.0gc e(N)
// Create table
esttab using "table1.tex", cells("mean(fmt(2) label(Prop./Mean)) sd(fmt(2) label(\emph{SD}) keep(isei age))") ///
                         refcat(educx1 "Education:" ///
                                femalex1 "Sex:", nolabel) ///
                         coeflabel(isei "Occupational status (ISEI)") ///
                         unstack ///
                         order(Total:* Male:* ) ///
                         nogap eqlabels(, span prefix(\multicolumn{@span}{c}{) suffix(}) erepeat(\cline{@span})) nonumber replace label ///
                         title("Descriptive statistics, \emph{N}~=~`n' \label{tab1}") ///
                         stats(N, fmt(%9.0gc) label(\emph{N})) ///
                         booktabs 
drop educx* femalex*  // Remove dummy variables created for table

Oct 11, 2019

Indent value labels of categorical variables for -esttab-

// Open Allbus cumulation
use hs01 iscd975 age sex ///
    using "ZA4586_v1-0-0.dta", clear

// Self-rated health
recode hs01 (4 5 = 1 "Poor health") ///
            (3 2 1 = 0 "Good health") ///
            (-1 -11 -9 = .) ///
            , gen(poorhealth)
label var poorhealth "Poor self-rated health"

// Education
recode iscd975 (5 = 5 "Tertiary") ///
               (4 = 4 "Post-secondary") ///
               (3 = 3 "Upper secondary") ///
               (2 = 2 "Lower secondary") ///
               (1 = 1 "Basic") (-32 = .) ///
               , gen(isced)
label var isced "Education"

// Age
recode age (-32 = .)
generate age10 = age/10
label var age10 "Age / 10"

// Sex
recode sex (1 = 0 "Male") ///
           (2 = 1 "Female") ///
           , gen(female)
label var female "Female sex"

// Indent value labels
labvalch3 female isced, prefix("\dumm ")

// Add this to Latex code
// % Indent for tables
// \newcommand*{\dumm}{\hspace*{0.5cm}}%
eststo clear eststo: regress poorhealth ib3.isced age10 i.female, robust esttab using table.tex, b(2) se(2) booktabs replace /// label nobaselevels nonumber /// modelwidth(25) varwidth(33) /// stats(N, fmt(%8.0gc)) /// refcat(1.isced "Education (ref. Upper secondary)" /// 1.female "Sex (ref. Male)", nol) /// title("Poor self-rated health regressed on education, age, and sex, linear probability model") // Alternative approach (that also works for .rtf tables) labvalch3 female isced, subst("\dumm " "") *ssc install elabel elabel define female isced (= #) (= " " + @) , modify // Note that the leading sapce don't seem to show up in a frequency table with -fre- esttab using table.rtf, b(2) se(2) replace /// label nobaselevels nonumber /// modelwidth(25) varwidth(33) /// stats(N, fmt(%8.0gc)) /// refcat(1.isced "Education (ref. Upper secondary)" /// 1.female "Sex (ref. Male)", nol) /// title("Poor self-rated health regressed on education, age, and sex, linear probability model")

Jun 6, 2017

Comparing AME's and the LPM

use doi hs01 age sex educ mstat using ZA5250_v2-0-0.dta, clear

// Poor health
recode hs01 (1 2 3 = 0 "Non-poor health") ///
            (  4 5 = 1 "Poor health") ///
            (-9 = .), gen(poorhealth)
label var poorhealth "Poor health"

// Female sex
recode sex (2 = 1 "Female") ///
           (1 = 0 "Male"), gen(female)
label var female "Female sex"

// Age
recode age (18/24 = 0 "18-24 y.") ///
           (25/34 = 1 "25-34 y.") ///
           (35/44 = 2 "35-44 y.") ///
           (45/54 = 3 "45-54 y.") ///
           (55/64 = 4 "55-64 y.") ///
           (65/74 = 5 "65-74 y.") ///
           (75/84 = 6 "75-84 y.") ///
           (85/97 = 7 "85-97 y.") ///
           (-32   = . ), gen(agecat)
label var agecat "Age"

// Education
recode educ (1 2 = 0 "Hauptschule or less") ///
            (  3 = 1 "Mittlere Reife") ///
            (4 5 = 2 "(Fach)Hochschulreife or more") ///
            (-41 -9 6 7 = .), gen(education)
label var education "Education"

// Marital status
recode mstat (1 6     = 2 "Married/cohabiting") ///
             (2 3 4 9 = 1 "Divorced, widowed etc.") ///
             (5       = 0 "Never married") ///
             (-9      = .), gen(married)
label var married "Marital status"

// Model 
eststo clear
  // AME
logit poorhealth i.female i.agecat i.education i.married 
margins, dydx(*) post
eststo
  // LPM
eststo: regress poorhealth i.female i.agecat i.education i.married, robust
esttab using amelpm.tex, drop(_cons) mtitle("AME" "LPM") label b(2) se(2) nonumbers booktabs ///
                         title("Predictors of poor self-rated health, Germany 2016 \label{tab1}") ///
                         addnote("\emph{Source}: Allbus 2016, doi: 10.4232/1.12754"  ///
                                 "AME: Average marginal effects, LPM: Linear probability model") ///
                         refcat(0.female "\emph{Sex}" ///
                                0.agecat "\emph{Age}" ///
                                0.education "\emph{Education}" ///
                                0.married "\emph{Marital status}", nolabel) ///
                         alignment(D{.}{.}{-1}) width(0.9\hsize) replace

Apr 4, 2016

Random graphs (70): Bar graphs for interaction plots

unzipfile "output7717034280080927434.zip", replace
use ESS1-6e01_0_F1, clear
*use cntry essround stfjbot wkhct using ESS1-6e01_0_F1, clear

// Select Round 5
keep if inlist(essround, 5)

// Fix country variable
encode cntry, gen(country)

// Satisfaction with WLB
rename stfjbot swlb

// Contracted working hours
recode wkhct (  0/20    = 1 "Marginal part-time") ///
             ( 21/34.75 = 2 "Substantial part-time") ///
             (35/220    = 0 "Full-time") ///
            , gen(parttime)
label var parttime "Working hours"

// Professional status
generate professional = .
replace  professional = (iscoco >= 1000 & iscoco <= 2999)
label var professional "Professional status"
label define professional 0 "Non-prof." 1 "Professional"
label val professional professional 

// Sex
recode gndr ( 2 =  1 "Female") ///
            ( 1 =  0 "Male") ///
            (.a = .a "No answer") ///
            , gen(female) label(female)
label var female "Gender"

// Select cases: Those in paid work and with a partner
keep if partner == 1 & mnactic == 1

// Are part-time workers more satisfied with their WLB than full-time employees?
qui regress swlb i.parttime i.country, cluster(country)
estimates store m1 

// Hypothesis 1b: The effect is stronger for marginal PT than substantial PT.
qui test 1.parttime == 2.parttime
local F = round(r(F), .001)
local p = round(r(p), .001)
local r = r(df)

qui margins, at(parttime=(0 1 2))
marginsplot, recast(bar) ///
             title("SWLB difference between full-time and part-time workers", size(large)) ///
             plotopts(fcolor(gs14) lcolor(black)) ytitle("Predicted SWLB") ylabel(6 (.5) 7.5, format(%6.1f) grid) ///
             name(noint, replace) xtitle("") ysize(3) ///
             note(" " ///
                  "Marginal and substantial part-time" ///
                  "differs significantly:" ///
                  "{it:F}(`r', `r(df_r)') = `F', {it:p} = `p'", ///
                  pos(11) ring(0) bmargin(small)) ///
             nodraw
    
// Are professional part-time workers less satisfied than non-professional part-time workers?
qui regress swlb i.parttime##i.professional i.country, cluster(country)
estimates store m2
qui margins, at(parttime=(0 1 2) professional=(0 1))
marginsplot, recast(bar) xdimension(professional) ///
             bydimension(parttime) byopts(row(1) noiyaxes imargin(zero) ///
    title("Interaction part-time status and professional status")) ///
    subtitle(, pos(6)) /// // Place label of by dimensions below plot 
             plotopts(fcolor(gs14) lcolor(black)) ytitle("Predicted SWLB") ylabel(6 (.5) 7.5, format(%6.1f)) ///
    name(int1, replace) xtitle("") ysize(3) nodraw
    
// Are women working part-time more satisfied with their SWLB than part-time working men?
qui regress swlb i.parttime##i.female i.country, cluster(country)
estimates store m3
qui margins, at(parttime=(0 1 2) female=(0 1))
marginsplot, recast(bar) xdimension(female) ///
             bydimension(parttime) byopts(row(1) noiyaxes imargin(zero) ///
    title("Interaction part-time status and gender")) ///
    subtitle(, pos(6)) /// // Place label of by dimensions below plot 
             plotopts(fcolor(gs14) lcolor(black)) ytitle("Predicted SWLB") ylabel(6 (.5) 7.5, format(%6.1f)) ///
    name(int2, replace) xtitle("") ysize(3) nodraw
// Output table and figure esttab m1 m2 m3 using test.tex, compress replace se label nomtitles /// indicate(Country dummies = *country) /// varwidth(30) interaction(" X ") /// title(Regression table\label{tab1}) /// booktabs graph combine noint int1 int2, col(1) ysize(9) ///
                               note("95% CI's based on cluster-robust standard errors")

Oct 3, 2015

Firebaugh (1997): Analyzing Repeated Surveys in Stata (ch. 3)




set maxvar 6000
use GSS7214_R4.DTA, clear

fre sample
// Try to recreate sample
drop if sample == 4 // FP 1970 Black oversample
drop if sample == 5 // BFP 1980 Black oversample
drop if sample == 7 // FP 1980 Black oversample

// Retirement status
fre wrkstat

generate retired_others  = (wrkstat == 5)
generate retired_workers = (wrkstat == 5)
replace  retired_workers = . if inlist(wrkstat, 7, 6, 8) // Exclude homemakers, 
                                                         // students, and others
// Spending on education
gen ed_toolittle = 0
replace ed_toolittle = 1 if nateduc == 1 & !missing(nateduc)
replace ed_toolittle = 0 if nateduc  > 1 & !missing(nateduc)
replace ed_toolittle = . if missing(nateduc)

gen ed_toomuch = 0
replace ed_toomuch = 1 if nateduc == 3 & !missing(nateduc)
replace ed_toomuch = . if missing(nateduc)

// Spending on social security
gen ss_toolittle = 0
replace ss_toolittle = 1 if natsoc == 1 & !missing(natsoc)
replace ss_toolittle = 0 if natsoc  > 1 & !missing(natsoc)
replace ss_toolittle = . if missing(natsoc)

gen ss_toomuch = 0
replace ss_toomuch = 1 if natsoc == 3 & !missing(natsoc)
replace ss_toomuch = 0 if natsoc  < 3 & !missing(natsoc)
replace ss_toomuch = . if missing(natsoc)

eststo clear
// Table 3.1

preserve
keep if year >= 1973 & year <= 1993
gen trend = year - 1973

eststo: logit ed_toomuch     c.trend##retired_others
eststo: logit ed_toolittle   c.trend##retired_others
 
eststo: logit ed_toomuch     c.trend##retired_workers
eststo: logit ed_toolittle   c.trend##retired_workers

esttab est1 est2 est3 est4 using table3.1.tex, replace varwidth(50) ///
       booktabs label ///
       mgroups("Retirees vs. others" "Retirees vs. workers", pattern(1 0 1 0) ///
       prefix(\multicolumn{@span}{c}{) suffix(})   ///
       span erepeat(\cmidrule(lr){@span}))         ///
       alignment(D{.}{.}{-1}) page(dcolumn) nonumber ///
       b(%9.3f) not ///
       drop(0b.retired_others ///
            0b.retired_others#co.trend ///
            0b.retired_workers ///
            0b.retired_workers#co.trend ///
   _cons) ///
    rename(1.retired_others 1.retired_workers ///
              1.retired_others#c.trend 1.retired_workers#c.trend) ///
       coeflabels(1.retired_workers "Initial difference, retirees minus workers/others" ///
               trend "Trend for retirees" ///
      1.retired_workers#c.trend "Trend difference retirees minus workers/others" ///
                  1.retired_others "Initial difference, retirees minus others" ///
      1.retired_others#c.trend "Trend difference retirees minus workers/others") ///
       mlabels("\multicolumn{1}{c}{Too much}" ///
            "\multicolumn{1}{c}{Too little}" ///
      "\multicolumn{1}{c}{Too much}" ///
            "\multicolumn{1}{c}{Too little}") ///
       order(1.retired_workers trend 1.retired_workers#c.trend) ///
    title("Table 3.1: Trend analysis for spending on education, 1973-1993: Logit coefficients")

restore

// Table 3.2
preserve
keep if year >= 1984 & year <= 1993
gen trend = year - 1984

eststo: logit ss_toomuch   c.trend##retired_others
eststo: logit ss_toolittle c.trend##retired_others
eststo: logit ss_toomuch   c.trend##retired_workers
eststo: logit ss_toolittle c.trend##retired_workers

esttab est5 est6 est7 est8 using table32.tex, replace varwidth(50) ///
       booktabs label ///
       mgroups("Retirees vs. others" "Retirees vs. workers", pattern(1 0 1 0) ///
       prefix(\multicolumn{@span}{c}{) suffix(})   ///
       span erepeat(\cmidrule(lr){@span}))         ///
       alignment(D{.}{.}{-1}) page(dcolumn) nonumber ///
       b(%9.3f) not ///
       drop(0b.retired_others ///
            0b.retired_others#co.trend ///
            0b.retired_workers ///
            0b.retired_workers#co.trend ///
   _cons) ///
    rename(1.retired_others 1.retired_workers ///
              1.retired_others#c.trend 1.retired_workers#c.trend) ///
       coeflabels(1.retired_workers "Initial difference, retirees minus workers/others" ///
               trend "Trend for retirees" ///
      1.retired_workers#c.trend "Trend difference retirees minus workers/others" ///
                  1.retired_others "Initial difference, retirees minus others" ///
      1.retired_others#c.trend "Trend difference retirees minus workers/others") ///
       mlabels("\multicolumn{1}{c}{Too much}" ///
            "\multicolumn{1}{c}{Too little}" ///
      "\multicolumn{1}{c}{Too much}" ///
            "\multicolumn{1}{c}{Too little}") ///
       order(1.retired_workers trend 1.retired_workers#c.trend) ///
    title("Table 3.2: Trend analysis for spending on social security, 1984-1993: Logit coefficients")
restore

Reference

Firebaugh, Glenn. 1997. Analyzing Repeated Surveys. Sage. doi: 10.4135/9781412983396