[2.2.a] Occupational prestige linear regression model
---------------------------
Variable | opmod
-------------+-------------
age | 0.284***
|
c.age#c.age | -0.002***
|
woman |
Women | -0.159
|
college |
College D.. | 16.238***
_cons | 31.359***
---------------------------
Legend: * p<.05; ** p<.01; *** p<.001
library(haven) # import Stata data and labelslibrary(dplyr) # data manipulationlibrary(ggplot2) # graphslibrary(modelsummary) # regression tableslibrary(marginaleffects) # predictions and marginal effectslibrary(cleanplots) # graph schemecleanplots_defaults()gss <-read_dta("https://tdmize.github.io/data/data/cda_gss.dta")# Keep only model vars and drop any missing data on themgss <- gss[c("occprest", "age", "woman", "college")]gss <- gss[complete.cases(gss), ]# Treat binary variables as factors using their value labelsgss <- gss |>mutate(woman =as_factor(woman), college =as_factor(college))age2mod <-lm(occprest ~poly(age, 2, raw =TRUE) + woman + college, data = gss)modelsummary(age2mod, stars =c("*"= .05, "**"= .01, "***"= .001),title ="[2.2.a] Occupational prestige linear regression model")
[2.2.a] Occupational prestige linear regression model
(1)
* p < 0.05, ** p < 0.01, *** p < 0.001
(Intercept)
31.359***
(0.389)
poly(age, 2, raw = TRUE)1
0.284***
(0.017)
poly(age, 2, raw = TRUE)2
-0.002***
(0.000)
womanWomen
-0.159
(0.101)
collegeCollege Degree
16.238***
(0.121)
Num.Obs.
58304
R2
0.246
R2 Adj.
0.246
AIC
456562.3
BIC
456616.1
Log.Lik.
-228275.128
F
4746.114
RMSE
12.14
Stata: Use factor syntax (c. for continuous IVs) and ## to specify polynomials.
R: Use the poly( , #) function to specify polynomials.
Interpreting polynomial IVs
The age2 coefficient is statistically significant—which is what we usually use to determine whether we should keep it in the model or not
If it was not significant, I would go back to a model with only age
The linear term (age) tells us the initial slope: here, a positive effect
The squared term (age2) tells us how the regression line’s slope will change eventually: here, become more negative/less positive
The coefficients don’t tell us at what age the effect becomes more negative; they do not tell us if the slope of age just becomes less positive or if it ever becomes negative (i.e., direction of effect reverses)
To answer these questions, we need to make and plot predictions
Stata: Use margins to calculate predictions, and marginsplot to make the graph.
qui margins, at(age=(20(5)80))marginsplot, /// recastci(rline) ciopts(lpat(dash) col(gs12)) ylab(38(2)46) ///title("[2.2.b] Predicted Occupational Prestige Based on Person's Age", size(medium)) ///subtitle("Quadratic Term for Age") ///ytitle("Occupational Prestige")
Variables that uniquely identify margins: age
plot_predictions(age2mod, by ="age",newdata =datagrid(age =seq(20, 80, 5), grid_type ="counterfactual")) +scale_y_continuous(breaks =seq(38, 46, 2), limits =c(38, 46)) +labs(title ="[2.2.b] Predicted Occupational Prestige Based on Person's Age",subtitle ="Quadratic Term for Age",x ="Age", y ="Occupational Prestige")
The marginal effect of age is now different depending on what starting and ending values are used to calculate MEage
Calculating marginal effects for nonlinear effects
di 31.36 + 0.28*40 - 0.002*1600 - 0.165*0 + 16.25*0
39.36
di 31.36 + 0.28*50 - 0.002*2500 - 0.165*0 + 16.25*0
40.36
di 40.36 - 39.36
1
di 31.36 + 0.28*70 - 0.002*4900 - 0.165*0 + 16.25*0
41.16
di 31.36 + 0.28*80 - 0.002*6400 - 0.165*0 + 16.25*0
40.96
di 40.96 - 41.16
-.2
31.36+0.28*40-0.002*1600-0.165*0+16.25*0
[1] 39.36
31.36+0.28*50-0.002*2500-0.165*0+16.25*0
[1] 40.36
40.36-39.36
[1] 1
31.36+0.28*70-0.002*4900-0.165*0+16.25*0
[1] 41.16
31.36+0.28*80-0.002*6400-0.165*0+16.25*0
[1] 40.96
40.96-41.16
[1] -0.2
Interpreting marginal effects for nonlinear effects
Interpretation is now limited to the specific value of age the marginal effect is calculated at:
For someone who is 40 years old, ten additional years of age is predicted to increase job prestige by about 1 point, accounting for other factors
For someone who is 70 years old, ten additional years of age is predicted to decrease job prestige by about 0.2 points, accounting for other factors
Interpretation tip: Note the initial clause specifying the starting age. These interpretations are only accurate for that specific age.
Summarizing nonlinear effects
A difficulty interpreting and presenting nonlinear effects is that the effect depends on where the effect is calculated [i.e., starting and ending values] and what type of change is being calculated
E.g., An instantaneous vs. one-unit vs. SD change will all yield different answers
And for categorical DVs, where the control variables are being held
How to summarize these effects? Two common solutions:
Marginal effect at the mean
Average marginal effect
Marginal effect at the mean (MEM): what is the effect of a change in a focal IV for the average person in your data
Average marginal effect (AME): on average—pooling and averaging across every observation in your data—what is the effect of a change in a focal IV
Marginal effects at the mean/modes (MEM)
MEMs have often been used, perhaps due to ease of computation and tradition
For a MEM, hold all control variables in \(\mathbf{x}_{- k}\) constant at their observed sample means/modes:
Is the mean/mode representative of what you want to know?
Is someone who is average on all variables realistic? Interesting?
If your theory suggests you should be looking at a specific type of person/observation (e.g., someone who is highly educated; someone who is working class; etc) then the effect for someone who is average on all characteristics may not accurately answer your question
Statistically, holding binary variables at their mean is not a problem
E.g., If \({\overline{x}}_{woman} = 0.60\), then the predictions are effectively weighted to reflect that 60% of the sample are women
However, substantively what does it mean to interpret a prediction for someone who is 0.60 a woman?
Stata will hold all variables, including binary/nominal variables, at their mean with the atmeans option. This is best practice and the way to get a true average effect
R’s marginaleffects sets binary/nominal variables to their modes, which I do not like and does not produce an average effect
Calculate the marginal effect at the mean (MEM) for the effect of aging from the mean age (≈46) to a SD above the mean (age ≈63) while holding the control variables constant at their means:
Variable | Obs Mean Std. dev. Min Max
-------------+---------------------------------------------------------
age | 58,304 46.165 17.15691 18 89
woman | 58,304 .5421412 .4982252 0 1
college | 58,304 .2256792 .4180324 0 1
mean(gss$age)
[1] 46.165
sd(gss$age)
[1] 17.15691
46.165+17.15691
[1] 63.32191
# MEM: newdata = "mean" holds the other variables at their means (modes for factors)comparisons(age2mod, variables =list(age =c(46.165, 63.32191)),newdata ="mean")
Estimate Std. Error z Pr(>|z|) S 2.5 % 97.5 %
0.293 0.0576 5.08 <0.001 21.4 0.18 0.406
Term: age
Type: response
Comparison: 63.32191 - 46.165
For the average person in the data, a standard deviation increase in age (about 17.2 years) is associated with a 0.293 increase in occupational prestige points
OR
For someone who is average on all characteristics included in the model, an additional standard deviation of age (about 17.2 years) is predicted to increase occupational prestige by 0.293 points
Centered vs uncentered changes
The example above is an uncentered change: from start value to start + \(\delta\)
\(\delta\) = amount of change
Usually, and especially for larger changes like a SD, best to center the change on the start value
Variable | Obs Mean Std. dev. Min Max
-------------+---------------------------------------------------------
age | 58,304 46.165 17.15691 18 89
di 46.165 + 17.15691
63.32191
hist age ife(sample), percentwidth(1) fcolor(none) lcolor(gs10) ///title("[2.2.d] Distribution of age for workers in the GSS") ///subtitle("Uncentered + SD change") ///xline(46.165, lcol(red)) xline(63.32, lcol(red)) ///text(2.3 50 "mean") text(2.3 70 "mean + SD")
(bin=71, start=18, width=1)
ggplot(gss, aes(age)) +geom_histogram(binwidth =1, fill =NA, color ="gray60") +geom_vline(xintercept =c(46.165, 63.32), color ="red") +annotate("text", x =c(50, 70), y =1600, label =c("mean", "mean + SD")) +labs(title ="[2.2.d] Distribution of age for workers in the GSS",subtitle ="Uncentered + SD change", x ="Age")
hist age ife(sample), percentwidth(1) fcolor(none) lcolor(gs10) ///title("[2.2.e] Distribution of age for workers in the GSS") ///subtitle("Centered + SD change") ///xline(46.165, lcol(red*.5)) xline(37.59, lcol(red)) xline(54.74, lcol(red)) ///text(2.4 30 "mean - SD/2") text(2.4 62 "mean + SD/2")
(bin=71, start=18, width=1)
46.165- (17.15691/2)
[1] 37.58655
46.165+ (17.15691/2)
[1] 54.74345
ggplot(gss, aes(age)) +geom_histogram(binwidth =1, fill =NA, color ="gray60") +geom_vline(xintercept =46.165, color ="pink") +geom_vline(xintercept =c(37.59, 54.74), color ="red") +annotate("text", x =c(30, 62), y =1600, label =c("mean - SD/2", "mean + SD/2")) +labs(title ="[2.2.e] Distribution of age for workers in the GSS",subtitle ="Centered + SD change", x ="Age")
Average marginal effects (AMEs)
We can compute a marginal effect for each observation in the data:
Note the subscript i’s in the formula which denote that the starting value, ending value, and control variable values can all vary across observations
\(\mathbf{x}_{- k,i}\) indicates that the control variable values are set to the observed values for that observation
E.g., If you are making a prediction for the 1st observation in the dataset who is a 45-year-old college educated woman, then make predictions at age = 45, college = 1, woman = 1 for that observation
Each ME calculation for each observation will use different values: those specific to that observation
For the start and end values:
The most common starting value is: whatever is observed
Common ending values for continuous IVs are:
Observed + 1
Observed + SD
For binary IVs, ending value is: opposite of what was observed
A set of predictions at the start and end values is made for every single observation in the data
The difference between these two indicates the marginal effect for that specific observation (MEi)
The average marginal effect (AME) averages these effects over all observations in the data:
Interpretations of AMEs are less awkward than MEM because you can now simply say what the effect is “on average” as you have calculated the effect for every observation in your sample and then averaged
Expression: Linear prediction, predict()
| age xb
----------+-------------------
1 | 46.2 42.850
2 | 63.3 43.143
Specified values where .n indicates no values specified with at()
| No at()
----------+---------
Current | .n
qui margins, at(age=(20(5)80))marginsplot, /// recastci(rline) ciopts(lpat(dash) col(gs12)) ///title("[2.2.f] Predicted Occupational Prestige Based on Person's Age", size(medium)) ///subtitle("Quadratic Term for Age") ///ytitle("Occupational Prestige") ///addplot(hist age if age < 80 & occprest < ., width(1) lcol(gs10) /// fcol(none) yaxis(2) yscale(range(0 0.15) off alt axis(2)) ///legend(off) ylab(38(2)46))
Variables that uniquely identify margins: age
plot_predictions(age2mod, by ="age",newdata =datagrid(age =seq(20, 80, 5), grid_type ="counterfactual")) +# histogram of age, scaled to sit along the bottom of the graphstat_bin(data =subset(gss, age <80), aes(x = age, y =after_stat(38+1.5* density /max(density))),geom ="step", binwidth =1, color ="gray60", inherit.aes =FALSE) +scale_y_continuous(breaks =seq(38, 46, 2), limits =c(38, 46)) +labs(title ="[2.2.f] Predicted Occupational Prestige Based on Person's Age",subtitle ="Quadratic Term for Age",x ="Age", y ="Occupational Prestige")
*Because we are calculating MEs for each observation, the AME is effectively weighted by where the data is; thus, it reflects both the effect (slope of line) and distribution of IV (where most of the data is)
In Stata, margins, mchange, and mecompare can all calculate marginal effects. mecompare has the most flexibility and capability
Default for all is AMEs; use option atmeans or covariates(atmeans) for MEMs
estrestore opmod
(results opmod are active now)
mecompare age college, covariates(atmeans)
Predicting: Linear prediction
Marginal effects (N_m1=58304)
| ME # Estimate SE P>|z|
---------------------------------+---------------------------------------
age + 1 (centered) |
m1 | 1 0.059 0.003 0.000
---------------------------------+---------------------------------------
college |
College Deg - No Col Deg |
m1 | 2 16.238 0.121 0.000
mecompare age college
note: models( ) omitted and e() holds a previous mecompare table; reusing the re
> gress model from that run. Type mecompare with no arguments to replay the tabl
> e instead.
Predicting: Linear prediction
Marginal effects (N_m1=58304)
| ME # Estimate SE P>|z|
---------------------------------+---------------------------------------
age + 1 (centered) |
m1 | 1 0.059 0.003 0.000
---------------------------------+---------------------------------------
college |
College Deg - No Col Deg |
m1 | 2 16.238 0.121 0.000
The marginaleffects package in R is extremely powerful, flexible, and works with most any model you can estimate in R*
The slopes (MEM) and avg_slopes (AME) functions estimate instantaneous rates of change for continuous IVs
The comparisons (MEM) and avg_comparisons (AME) functions estimate effects for nominal/binary IVs, and can be used to estimate discrete changes for continuous IVs
For a MEM, specify that control variables be held at their mean/modes with:
newdata = “mean”
No special options needed for an AME as these are the default for the avg_ functions
Binary and nominal predictors work seamlessly with avg_comparisons
avg_comparisons(age2mod, variables ="college")
Estimate Std. Error z Pr(>|z|) S 2.5 % 97.5 %
16.2 0.121 134 <0.001 Inf 16 16.5
Term: college
Type: response
Comparison: College Degree - No Col Degree
avg_slopes reports the average instantaneous rate of change
avg_slopes(age2mod, variables ="age")
Estimate Std. Error z Pr(>|z|) S 2.5 % 97.5 %
0.0589 0.00317 18.6 <0.001 253.8 0.0527 0.0651
Term: age
Type: response
Comparison: dY/dX
On average, a one-year increase in age is predicted to increase occupational prestige by 0.059 points
Workers with college degrees have jobs that are about 16 points more prestigious than workers without college degrees
mecompare defaults to a one-unit change for continuous IVs
Can specify various custom amounts, e.g., a standard deviation with amount(sd), or a specific \(\delta\) with amount(#), or an instantaneous rate of change with amount(rate)
mecompare age, amount(sd)
note: models( ) omitted and e() holds a previous mecompare table; reusing the re
> gress model from that run. Type mecompare with no arguments to replay the tabl
> e instead.
Predicting: Linear prediction
Marginal effects (N_m1=58304)
| ME # Estimate SE P>|z|
---------------------------------+---------------------------------------
age + SD (centered) |
m1 | 1 1.010 0.054 0.000
Customizing amounts of change with marginaleffects
avg_comparisons has some built-in amounts you can specify for an average marginal effect with continuous IVs
E.g., Specify sd for one standard deviation or 2sd for two standard deviations, or specify any custom \(\delta\) amount by listing the number
Estimate Std. Error z Pr(>|z|) S 2.5 % 97.5 %
0.294 0.0158 18.6 <0.001 253.8 0.263 0.325
Term: age
Type: response
Comparison: +5
On average, a standard deviation increase in age (about 17.2 years) is predicted to increase occupational prestige by about 1 point
Interpretation tip: The first time you report a +SD marginal effect, good practice to remind readers of the size of a SD. This will vary drastically across samples and is needed to contextualize the effect.