This page follows the quantitative part of Methods of Social Research for Channel B (weeks 8 to 13), lecture by lecture. It collects the commands we ran in class in DAX, the browser-based environment Luiss uses for this course, and explains how to read their output. You type Stata-style commands; DAX translates them into R behind the scenes.
Every section has the same structure:
The best way to use this page. Keep it open next to DAX. Copy one block, run it, and read the output before moving on. The commands are the easy part: what matters for the exam is reading the output.
use and the full web address. Nothing needs to be
uploaded:use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/worldcup_democracy.dta", clear
describe
DAX is not desktop Stata. It understands a large
part of Stata syntax, but not all of it. Everything on this page works
in DAX. Two rules to remember from the start: keep comments (lines
starting with *) on their own line, never
after a command; and if a command fails, check the DAX survival kit at the end.
All datasets load with
use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/<file>", clear.
You never need to download them.
| Week | File | What one row is |
|---|---|---|
| 8 | worldcup_democracy.dta |
a national team in one World Cup edition (537) |
| 9 | chile1988.dta, turnout.dta |
a Chilean voter in 1988 (2,700); a US election (14) |
| 10 | vignettes.dta, afghan.dta |
a respondent in China or Mexico (781); an Afghan respondent (2,754) |
| 10 | battery.dta |
a respondent who answered five personality items (2,709) |
| 10 | chile_samples.dta, afghan_village.dta |
one simulated sample (500); an Afghan village (1,864) |
| 11 | ches2024_lab.dta |
a European political party in 2024 (245): the in-class lab |
| 11 | resume.dta |
a fictitious CV (4,870) |
| 12 | minwage.dta, polarization.dta |
a fast-food restaurant (358); a US Congress (33) |
| 12 | face.dta |
a US Senate race, 2000–2006 (119) |
| 12 | gss2021_marital.dta |
a US adult in the 2021 General Social Survey (3,624) |
| 12–13 | gss2021_lab.dta |
a US adult in the 2021 General Social Survey (3,500) |
| 13 | msr_survey_games.dta |
a student in our class survey on video games (20) |
Science is a method: a loop from question to theory, hypotheses, observation and evaluation. A hypothesis is useful only if it is falsifiable: you must be able to say in advance which evidence would count against it.
Our running question (Lecture 8.3): does a country’s political regime affect its chances of playing in, and winning, the World Cup? Sportswashing predicts that autocracies do better (H1a); democratic capacity predicts that democracies do better (H1b).
use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/worldcup_democracy.dta", clear
describe
summarize goals
tab1 year
tab1 winner finalist host
What you should see. 537 observations: one row is
one national team in one World Cup edition (the unit of
analysis), 23 editions from 1930 to 2026.
tab1 year shows 13 teams in 1930 and 48 in 2026.
Read it. describe tells you what you
actually opened; run it every time. In DAX summarize always
needs at least one variable. The tournament itself changed over time (13
teams, then 48): keep that in mind when you compare editions.
summarize polyarchy
histogram polyarchy
summarize winner
Read it. polyarchy (V-Dem electoral
democracy index, 0 to 1) is our X. DAX draws one bar for each distinct
value, so the histogram looks like a barcode: look where the bars crowd
together. There are many very autocratic and many very democratic teams,
fewer in between, and the mean hides this. For a 0/1 variable like
winner, the mean is the proportion of
ones: 23 champions out of 537 appearances, about 0.04.
recode polity2 (-10/-6 = 0) (-5/5 = 1) (6/10 = 2), generate(regime)
label define reglbl 0 "Autocracy" 1 "Anocracy" 2 "Democracy"
label values regime reglbl
tab1 regime
* every champion is also a finalist: 0 other, 1 runner-up, 2 champion
generate outcome = winner + finalist
label define outlbl 0 "Other participant" 1 "Runner-up" 2 "Champion"
label values outcome outlbl
tab1 outcome
tab2 winner finalist
Read it. The concept (democracy) becomes a variable
through explicit decisions: here, the conventional Polity5 cut-offs.
Always check a variable you just built:
tab2 winner finalist confirms that every champion is also a
finalist.
scatter polyarchy year
ttest polyarchy, by(winner)
ttest polyarchy, by(finalist)
tab2 regime winner, column
correlate polyarchy gdppc goals
What you should see.
ttest polyarchy, by(winner): about 0.59 for the other
appearances and 0.67 for the champions, t = −1.25, p = 0.224. By
finalist: 0.58 and 0.69, t = −2.54, p = 0.014. The
correlation between polyarchy and gdppc is
about 0.55.
Read it.
ttest prints the mean of each group
first: read them before the p-value. DAX computes group 0 minus group 1,
so when group 1 has the higher mean, t is negative.Evaluation. H1a finds no support; H1b survives, weakly, and only for reaching the final. “Not significant” does not mean “no effect”: it means the evidence is too thin to tell the groups apart.
polyarchy and polity2
agree?polity2 (6 or more =
democracy) and cross it with winner.ttest goals, by(host)
correlate polyarchy polity2
recode polity2 (-10/5 = 0) (6/10 = 1), generate(democracy)
label define demlbl 0 "Non-democracy" 1 "Democracy"
label values democracy demlbl
tab2 democracy winner, column
Hosts score clearly more, but hosts are not chosen at random (they are often rich, strong football nations) and they play at home. The two democracy measures correlate strongly (about 0.93) but not perfectly: every measure is a decision.
A concept becomes a variable through an operational definition (the question, the coding rule, the unit of measurement). The level of measurement decides which operations make sense:
| Level | Example | Legitimate operations |
|---|---|---|
| Nominal | vote intention | equal / different |
| Ordinal | education level | also greater / less than |
| Interval / ratio | age, income | also differences, means |
DAX does not know the level of measurement of your variables. You do.
The chile1988 data: 2,700 Chilean adults interviewed a
few months before the 1988 plebiscite on General Pinochet.
use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/chile1988.dta", clear
describe
tab1 vote
summarize vote
Read it. vote is nominal (1 abstain, 2
No, 3 undecided, 4 Yes). DAX happily computes its mean (2.84): the
number is correct and meaningless. A Yes voter is not
“more” of anything than a No voter.
tab1 educ_raw
recode educ_raw (1=1) (3=2) (2=3), generate(educ)
label define edlbl 1 "Primary" 2 "Secondary" 3 "Post-secondary"
label values educ edlbl
tab1 educ
tab2 educ_raw educ
Read it. The original file coded education
alphabetically (Primary, Post-secondary, Secondary), so post-secondary
sat in the middle. An ordinal variable is ordinal only if its codes are
in the right order. tab2 educ_raw educ checks that every
old value lands in exactly one new value.
recode age (18/29=1) (30/49=2) (50/70=3), generate(agegrp)
label define agelbl 1 "18-29" 2 "30-49" 3 "50-70"
label values agegrp agelbl
tab1 agegrp
recode sex (1=1) (2=0), generate(female)
label define femlbl 0 "Male" 1 "Female"
label values female femlbl
summarize female
Read it. From agegrp you can never
recover the exact age: you can always go down a level
of measurement, never back up. For a 0/1 dummy the mean
is the proportion of ones: 0.51, so 51% of respondents are women. In DAX
build dummies with recode, and always define new
labels.
turnout.dta compares the turnout reported in the
American National Election Studies (ANES) with official turnout in 14 US
elections.
use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/turnout.dta", clear
generate vep_rate = total / vep * 100
generate bias = anes - vep_rate
summarize anes vep_rate bias
scatter bias year
What you should see. bias: mean 16.84,
minimum 8.58, maximum 22.49.
Read it. The minimum is positive: the survey overestimates turnout in every election, by 8 to 22 points. The error is systematic, not random: the instrument is reliable (stably wrong) but not valid. Usual suspects: social desirability and non-response.
If statusquo (an index of support for the regime) is
valid, declared Yes voters should score much higher than declared No
voters.
use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/chile1988.dta", clear
summarize statusquo if vote == 2
summarize statusquo if vote == 4
summarize statusquo
Read it. No voters average about −0.91, Yes voters about +0.94; the whole sample has mean 0 and standard deviation 1. The index separates the known groups very clearly.
Before any relationship, describe each variable on its own: its distribution (how often each value occurs), its centre (mode, median, mean), its shape (symmetric or skewed, one peak or two) and its spread (range, interquartile range, standard deviation). Which statistics make sense depends on the level of measurement.
use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/chile1988.dta", clear
recode educ_raw (1=1) (3=2) (2=3), generate(educ)
label define edlbl 1 "Primary" 2 "Secondary" 3 "Post-secondary"
label values educ edlbl
tab1 vote
tab1 educ
histogram vote
histogram age
What you should see. In tab1 vote, 889
respondents will vote No: 35.11% in the Valid percent
column, 32.93% in the Percent column.
Read it. DAX gives two percentages. Valid
percent is out of those who answered (2,532);
Percent is out of all 2,700 respondents, with the 168
missing answers in the <NA> row. Always ask: percent
of what? For an ordered variable like educ the cumulative
column also means something.
summarize age income statusquo
histogram income
histogram statusquo
What you should see. Age: mean 38.5, median 36.
Income: mean 33,876, median 15,000. statusquo: mean 0,
standard deviation 1.
Read it.
statusquo has two humps: opponents and
supporters of the regime, few in between. A mean of 0 describes almost
nobody.summarize already shows the median (last
column). summarize, detail adds nothing, and DAX does not
compute skewness: compare mean and median, then plot.tab1 age
tab1 income
Read it. DAX does not print percentiles, so read
them off the Cum. column of tab1: the 25th
percentile is the first value where the cumulative percentage reaches
25%, the 75th where it reaches 75%. For age: 26 and 49, so the
interquartile range is 23 years. For income: 7,500 and
35,000 pesos. The IQR, like the median, is not affected by a few extreme
values; the standard deviation is.
population is the size of the respondent’s community. Is
its mean above or below the median? Almost half the respondents share
the maximum value: what does that suggest about how the variable was
recorded?
summarize population
tab1 population
histogram population
Mean about 152,000, median 175,000: here the mean is below the median. About 48% of respondents have exactly 250,000, the maximum. Everybody living in a large city was given the same value: the variable is top-coded, so it cannot tell a city of 300,000 from one of 3 million.
A survey turns concepts into questions and answers into response categories. Two things can go wrong at this step: respondents may read the categories differently, and some may not answer at all, or not answer honestly.
use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/vignettes.dta", clear
describe
* own political say: 1 = no say at all ... 5 = unlimited say
ttest self, by(china)
* the same scale, applied to an identical hypothetical person (Moses)
ttest moses, by(china)
* where do I place myself relative to Moses?
generate relative = self - moses
ttest relative, by(china)
What you should see. self: Mexico 1.83,
China 2.62. moses: Mexico 1.78, China 3.49.
relative: Mexico +0.04, China −0.87.
Read it. Taken at face value, Chinese respondents report more political say than Mexicans. But they also give much more say to Moses, the same hypothetical person: the categories mean something different in the two countries. Relative to Moses, Chinese respondents place themselves below him and Mexicans about level with him. After anchoring, the conclusion is reversed.
afghan.dta: 2,754 civilians interviewed in 2011 in five
Afghan provinces.
use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/afghan.dta", clear
summarize age educyears violisaf violtaliban income
tab1 violisaf
tab1 violtaliban
tab2 province violtaliban
What you should see. In summarize, the
Obs column: 2,754 for age and education, 2,729 for harm
by the international forces (violisaf), 2,700 for harm by
the Taliban (violtaliban), 2,600 for income.
Read it. The Obs column counts the valid
answers. Nonresponse is low overall, but it is not spread
evenly: compare the row totals of tab2 province violtaliban
with tab1 province. Most of the missing answers about the
Taliban come from Helmand and Uruzgan, the two most violent provinces.
The people who do not answer are not a random group.
Asking directly “do you support the foreign forces?” is dangerous in a war zone. Each respondent was randomly given one of three lists and asked only how many items they support. The control list has 3 items; another list adds the sensitive item (ISAF, the international forces).
tab1 listgroup
tab2 listresponse listgroup
ttest listresponse, by(isafcontrol)
What you should see. 918 respondents in each list. Mean number of items: 1.5196 with the control list, 1.5686 with ISAF added.
Read it. Because the lists were assigned at random, the two groups are alike except for the extra item. The difference in means, 1.5686 − 1.5196 = 0.049, estimates the share who support the foreign forces: about 5%, without anybody having to say so.
One question is a noisy measure of an abstract concept. A Likert scale adds up several items that measure the same thing. Before adding them: check that they all point in the same direction, reverse those that do not, and check that they hang together (Cronbach’s alpha).
battery.dta: five statements on agreeableness answered
by 2,709 people (1 = very inaccurate … 6 = very accurate).
use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/battery.dta", clear
describe
summarize a1 a2 a3 a4 a5
correlate a1 a2 a3 a4 a5
Read it. Items a2–a5 have means between 4.55 and 4.80 and correlate positively. Item a1 has a mean of 2.41 and correlates negatively with all the others: “Am indifferent to the feelings of others” measures agreeableness in the opposite direction.
generate a1r = 7 - a1
* DAX copies the labels of a1 onto a1r: replace them with an empty set
label define nolab 99 "none"
label values a1r nolab
tab2 a1 a1r
correlate a1r a2 a3 a4 a5
generate agree = a1r + a2 + a3 + a4 + a5
label values agree nolab
summarize agree
histogram agree
What you should see. After reversing, all
correlations are positive (mean 0.33). agree runs from 5 to
30, with mean 23.2 and median 24.
Read it.
We study a few hundred people to say something about millions. Random sampling makes this possible: every sample is a little wrong, but on average it is right, and we can say how wrong it is likely to be (the sampling error). A random sample is unbiased; a large non-random sample is not.
chile_samples.dta contains 500 random
samples drawn from 2,531 Chilean voters, with samples of 50,
200 and 1,000 people. In that population the true share of No voters is
35.12%.
use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/chile_samples.dta", clear
describe
* DAX rounds to two decimals: turn the shares into percentages first
generate pctno50 = pno50*100
generate pctno200 = pno200*100
generate pctno1000 = pno1000*100
summarize pctno50 pctno200 pctno1000
histogram pno50
histogram pno1000
What you should see (in percentage points).
| Sample size | Mean of the 500 estimates | Std. dev. (= sampling error) | Min | Max |
|---|---|---|---|---|
| 50 | 35.10 | 6.67 | 16.0 | 56.0 |
| 200 | 35.26 | 3.24 | 27.0 | 46.0 |
| 1,000 | 35.01 | 1.21 | 31.8 | 40.5 |
Read it. All three means land on the true 35.1%: random sampling is unbiased. What changes with the sample size is the spread: one sample of 50 said 16%, another 56%. Larger samples are wrong by less. Each histogram has its own axis: read the numbers on the horizontal axis before comparing them.
There is no list of Afghan civilians: the survey sampled districts,
then villages, then households. afghan_village.dta lists
1,864 villages and whether each was surveyed.
use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/afghan_village.dta", clear
tab1 surveyed
ttest altitude, by(surveyed)
generate logpop = log(population)
ttest logpop, by(surveyed)
What you should see. 204 villages surveyed out of 1,864. Mean altitude 1,544 metres in both groups (p = 0.99). Log population 6.05 vs 6.08 (p = 0.72).
Read it. On what we can observe, the surveyed villages look like the others. Population is very skewed, so it is compared on the log scale. This is a check, not a proof: it can only use variables we observe.
altitude into two groups (below 1,500 metres;
1,500 or more), label them and cross the new variable with
surveyed (column percentages). Is the share of high
villages similar in the two groups?altitude and population
separately for sampled and non-sampled villages. Why do the mean
populations differ more than the medians?use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/afghan_village.dta", clear
recode altitude (0/1499 = 1) (1500/4000 = 2), gen(highland)
label define hl 1 "Below 1500 m" 2 "1500 m or more"
label values highland hl
tab2 highland surveyed, col
by surveyed: summarize altitude population
by group:, not bysort group:.In the lab (Lecture 11.2, 18 November) you used the commands of weeks
8–10 on a new dataset: the Chapel Hill Expert Survey
2024, one row per European political party (245 parties).
eu_position runs from 1 (strongly opposed to European
integration) to 7 (strongly in favour); family is the party
family; vote the vote share.
use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/ches2024_lab.dta", clear
describe
* reverse the scale: 1 = strongly pro-EU, 7 = strongly anti-EU
generate euroscep = 8 - eu_position
summarize euroscep
* a dummy for the radical right (family 1)
recode family (1=1) (2/11=0), gen(radright)
label define rrlab 0 "Other family" 1 "Radical right"
label values radright rrlab
tab1 radright
ttest euroscep, by(radright)
summarize vote
ttest vote, by(radright)
What you should see. euroscep: mean
3.04, median 2.48, sd 1.70. 44 radical-right parties (17.96%).
Euroscepticism: other families 2.52, radical right 5.40. Vote share:
mean 10.16%, median 6.90%; other families 10.03%, radical right
10.72%.
Read it.
family is
nominal, vote is a ratio variable.Saying that X causes Y means that changing X would change Y. We need covariation, the right causal direction and control of other causes. Every unit has two potential outcomes, with and without the treatment, but we observe only one: the other is the counterfactual. Random assignment solves the problem on average: the groups are alike on everything, measured or not, and the difference in means estimates the average causal effect.
Bertrand and Mullainathan (2004) sent about 5,000 fictitious CVs to real job ads in Boston and Chicago. The first name was assigned at random: stereotypically Black or stereotypically white.
use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/resume.dta", clear
describe
tab1 black
tab2 black call, row
ttest call, by(black)
* balance check: is the share of female names the same in both groups?
ttest female, by(black)
What you should see. White names:
9.65% called back; Black names: 6.45%.
ttest: 0.0965 and 0.0645, p < 0.001. Female names: 76.4%
and 77.5% (p = 0.38).
Read it.
ttest
compares two callback rates.* 0 = white man, 1 = Black man, 2 = white woman, 3 = Black woman
generate group = black + 2*female
label define grouplab 0 "white man" 1 "Black man" 2 "white woman" 3 "Black woman"
label values group grouplab
tab1 group
tab2 group call, row
Read it. Women: 9.89% vs 6.63% (3.3 points); men:
8.87% vs 5.83% (3.0 points). Almost the same discrimination. Only 1,124
CVs carry a male name, against 3,746 female names: the estimate for men
is less precise. (In DAX generate … if does not work and
ttest does not accept if: that is why we build
one group variable.)
Most causes we care about (a law, a religion, a regime) cannot be assigned at random. In an observational study nobody assigns X: the comparison is realistic, but the groups may differ in other ways. Every comparison assumes a counterfactual: name the assumption. Then we describe relationships: contingency tables for two categorical variables, scatterplots and the correlation r for two interval variables.
In April 1992 New Jersey raised its minimum wage; neighbouring Pennsylvania did not. Card and Krueger (1994) surveyed fast-food restaurants on both sides of the border.
use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/minwage.dta", clear
describe
* did the law change wages? (nj: 0 Pennsylvania, 1 New Jersey)
ttest wageBefore, by(nj)
ttest wageAfter, by(nj)
* the outcome: share of full-time workers after the law
generate shareafter = fullAfter / (fullAfter + partAfter)
ttest shareafter, by(nj)
What you should see. Starting wage after the law: Pennsylvania 4.61, New Jersey 5.08 (before: 4.65 and 4.61). Full-time share after the law: Pennsylvania 0.27, New Jersey 0.32 (p = 0.16).
Read it. The law did raise wages in New Jersey, and
New Jersey restaurants did not lose full-time jobs: their share is 4.8
points higher. But the law was not assigned at random: this is an
association, and it assumes that, without the law, the
two states would look alike. (In this version of the file the variables
are called wageBefore, wageAfter,
fullAfter, partAfter: type them exactly like
that.)
gss2021_lab.dta: 3,500 American adults.
gunlaw: should a police permit be required before buying a
gun? (1 favor, 2 oppose).
use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/gss2021_lab.dta", clear
tab2 sex gunlaw, row
tab2 gunlaw sex, col
What you should see. In favour: men 62.99%, women 70.88%. Of those in favour, 58.04% are women.
Read it. Put the independent variable (sex) in the rows and use row percentages, then compare down a column: women are 7.9 points more in favour. The second table gives the same percentages with the variables swapped (and column percentages). “58% of those in favour are women” answers a different question: it also depends on how many women are in the sample.
polarization.dta: one row per US Congress, 1948–2012.
polarization is the distance between the median Republican
and the median Democrat; gini measures income
inequality.
use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/polarization.dta", clear
describe
scatter polarization gini
correlate polarization gini
correlate polarization gini year
What you should see. r(polarization, gini) = 0.94. But also r(polarization, year) = 0.94 and r(gini, year) = 0.87.
Read it. r runs from −1 to +1 and measures how closely the points cluster around a straight line. 0.94 is very high, but both variables rise over time, and two variables that trend together will correlate whether or not one causes the other: the same trap as the World Cup in week 8.
cappun: 1
favor, 2 oppose)?use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/polarization.dta", clear
correlate repmedian demmedian
use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/gss2021_lab.dta", clear
tab2 sex cappun, row
Correlation tells us how closely two variables move together. Regression tells us by how much Y is expected to change when X changes by one unit, and lets us predict Y:
Y = α + βX + ε
Todorov et al. (2005) showed people the faces of the two main
candidates in US Senate races for one second and asked which one looked
more competent. d_comp is the share who
chose the Democrat.
use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/face.dta", clear
describe
generate d_share = d_votes / (d_votes + r_votes)
generate r_share = r_votes / (d_votes + r_votes)
generate diff_share = d_share - r_share
summarize diff_share d_comp
scatter diff_share d_comp
correlate diff_share d_comp
regress diff_share d_comp
What you should see. r = 0.433. In
regress: d_comp 0.660*** (0.127), constant
−0.312*** (0.066); 119 observations, R² = 0.187.
Read it.
diff_share is the Democrat’s two-party margin: positive
when the Democrat won.regress d_comp diff_share gives a different slope (0.284)
but the same R².DAX has no predict: type the coefficients yourself.
generate pred = -0.312 + 0.660 * d_comp
generate resid = diff_share - pred
summarize pred resid
* does the line pick the right winner?
generate d_win = (diff_share > 0)
generate d_win_pred = (pred > 0)
generate correct = (d_win == d_win_pred)
summarize correct
What you should see. The residuals average 0.
correct has a mean of 0.72: the line picks the winner in 86
of 119 races.
Read it. With d_comp = 0.5 the predicted margin is
−0.312 + 0.660 × 0.5 = +0.018, almost a tie. The largest residuals are
long-serving incumbents in safe states (Kennedy in Massachusetts 2000,
Stevens in Alaska 2002): everything the faces do not see ends up in the
residual. (The comparisons in generate give TRUE/FALSE;
that is fine for a mean, but for dummies you want to tabulate or label,
use recode.)
Prediction is not explanation. Nobody randomised the faces. Incumbents may look more confident and win more often for other reasons. Whether a coefficient is a causal effect depends on the design, not on the software.
With more than one predictor, each coefficient is the expected change in Y for a one-unit change in that X, holding the other predictors constant:
Y = α + β₁X₁ + β₂X₂ + … + ε
A coefficient changes when we add a predictor only if the new X is related both to the old X and to Y. A nominal predictor enters as a set of 0/1 dummies, one per category except the reference. R² tells us how much of the variation in Y the model accounts for.
gss2021_marital.dta: 3,624 respondents. Y =
polviews (1 extremely liberal … 7 extremely conservative).
X: years of schooling (educ), age, family
income compared with others (finrela, 1–5),
sex (1 male, 2 female), marital (1 married, 2
widowed, 3 divorced, 4 separated, 5 never married).
use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/gss2021_marital.dta", clear
describe
summarize polviews educ age finrela
regress polviews educ
regress polviews finrela
correlate polviews educ age finrela
regress polviews educ age finrela
What you should see.
| Alone (simple regression) | With the other two | |
|---|---|---|
| educ | −0.089 | −0.088*** |
| age | +0.014*** | |
| finrela | −0.107 | −0.017 |
| Constant | 4.568*** |
R² = 0.026 with educ alone, 0.050 with all three.
r(educ, finrela) = 0.36; r(educ, age) = 0.01.
Read it. People from richer families look more
liberal, but richer families also give their children more schooling.
Among people with the same education and age, income is
almost unrelated to political views: finrela drops from
−0.107 to −0.017 and loses its stars. educ does not move,
because age and education are unrelated. Prediction by hand: a
25-year-old with 18 years of schooling and finrela = 3 gets
4.568 − 0.088 × 18 + 0.014 × 25 − 0.017 × 3 = 3.28.
tab1 marital
* wrong: treats the codes 1-5 as quantities
regress polviews marital
* right: one dummy per category, married (1) as the reference
regress polviews i.marital
What you should see.
regress polviews marital: −0.154, a number with no meaning.
regress polviews i.marital: constant 4.114 (the mean of
married respondents); widowed +0.137, divorced −0.104, separated −0.031,
never married −0.654***.
Read it. marital is nominal: DAX runs
the first regression anyway, because it does not know the level of
measurement. With i., each coefficient is the
difference from the reference group: the never married
are 0.65 points more liberal than the married (3.46 vs 4.11). With
k categories, i. creates k − 1
dummies.
* ib5.marital does not work in DAX: give the reference the lowest code
recode marital (5=0), gen(marital_nm)
label define nmlab 0 "never married" 1 "married" 2 "widowed" 3 "divorced" 4 "separated"
label values marital_nm nmlab
regress polviews i.marital_nm
Read it. Now the constant is the mean of the never married (3.460) and every coefficient is a difference from them: married +0.654, the same gap with the sign reversed.
regress polviews educ age finrela i.sex i.marital
What you should see. educ −0.090, age 0.008, finrela −0.065, female −0.202, never married −0.599, divorced −0.211; constant 5.358; R² = 0.074.
Read it. Every coefficient depends on which other predictors are in the model: never married goes from −0.65 to −0.60, age from 0.014 to 0.008 (the never married are younger, the widowed older).
R² = 1 − (sum of squared residuals) / (total sum of squares): the share of the variation in Y the model accounts for. Here it grows from 0.026 to 0.050 to 0.074. It never falls when you add a predictor (adjusted R² adds a small penalty). Political views are hard to predict from demographics: a low R² is normal in survey data and does not make the coefficients wrong. R² is about prediction, not about importance or causation.
Use the full model. Respondent C is a woman, 40 years old, 16 years
of schooling, finrela = 3, never married. Respondent D is a
man with the same age, schooling and income, married. Predict their
polviews.
D is in both reference groups (man, married), so all the dummies are 0: 5.358 − 0.090 × 16 + 0.008 × 40 − 0.065 × 3 = 4.04. C adds female and never married: 4.04 − 0.202 − 0.599 = 3.24. The gap of 0.80 points is the sum of the two dummies.
A difference in a sample is not automatically a difference in the population: every sample is a little wrong (week 10). A hypothesis test tells us when a sample result is good evidence about the population.
use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/gss2021_lab.dta", clear
describe
by sex: summarize polviews
ttest polviews, by(sex)
What you should see. In ttest: 4.0573
(men), 3.8741 (women), t = 3.4983 (3325), p = 0.0005.
Read it. DAX prints the two means, t with its degrees of freedom (Welch test) and the two-sided p-value. The rest you compute yourself:
p = 0.0005 < 0.05: we reject H0. Women place themselves slightly to the left of men: significant, but small (3% of the scale).
ttest polviews = 4
What you should see. Mean 3.9563, t = −1.6791 (3499), p = 0.0932.
Read it. p = 0.093 > 0.05: we fail to reject H0 (μ = 4). That does not prove that the mean is 4: the interval, about [3.91, 4.01], also contains 3.92. Failing to reject is not proving.
regress polviews attend
generate female = sex - 1
* the new variable keeps the labels of sex: give it its own
label define femlab 0 "male" 1 "female"
label values female femlab
tab1 female
regress polviews female
regress polviews i.degree
What you should see. attend: 0.155***
(0.009). female: −0.183*** (0.052), constant 4.057.
Read it.
regress polviews age
generate age10 = age / 10
regress polviews age10
Read it. age: 0.014 (0.001), so t by
hand would be 14; the true t is about 9.4. DAX rounds to three decimals
and a standard error of 0.0015 is printed as 0.001. Rescale the variable
(decades instead of years: 0.141 with SE 0.015) and t by hand works
again.
What a p-value is not.
cappun) differ in ideology? Do supporters and opponents of
gun permits (gunlaw) differ in religious attendance?regress polviews i.degree, which degree groups
differ significantly from the reference (less than high school)?ttest polviews, by(cappun)
ttest attend, by(gunlaw)
The whole cycle of the course in one study, with our own data (Lecture 13.2). Research question: why do some students support limiting violent video games for teenagers, while others oppose it?
support: mean of two proposals
(sup_ban, no violent games to under-18s;
sup_limit, a 2-hour daily limit), 0 oppose … 10
support.gamer_d, game_hours).pater, 0–10).harmful.msr_survey_games.dta: 20 questionnaires analysed (1
excluded for failing the attention check).
use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/msr_survey_games.dta", clear
describe
summarize support sup_ban sup_limit game_hours pater
tab1 gamer
tab1 harmful
recode sup_ban (0/4 = 1) (5 = 2) (6/10 = 3), generate(ban3)
label define ban3l 1 "Oppose (0-4)" 2 "Middle (5)" 3 "Support (6-10)"
label values ban3 ban3l
tab2 gamer ban3, row
What you should see. support: mean
5.20. Gamers: No 11, Sort of 6, Yes 3. Versions: B 8, A 12. In
tab2, 72.73% of non-gamers support the ban; none of the
“sort of” and “yes” gamers do.
ttest support, by(gamer_d)
tab2 female gamer, row
ttest support, by(female)
What you should see. Support: others 5.76, gamers 2.00; t = 3.27 (3), p = 0.038. Women: 81.82% non-gamers, men 22.22%. Support: men 4.11, women 6.09, p = 0.10.
Read it. Gamers support the restrictions 3.8 points less, and the difference is significant, but there are only 3 gamers. And gamers are mostly men, while women support the restrictions more: is it gaming or gender? That is a job for multiple regression.
* (a) did the message get through?
tab2 harmful manip, row
* (b) balance: only variables measured before the article
ttest gamer_d, by(harmful)
ttest pater, by(harmful)
* (c) the effect on the main outcome
ttest support, by(harmful)
What you should see. 83% of A readers and 63% of B readers recalled what their article said. Balance: no significant differences (p = 0.38 and 0.73). Effect: B 5.31, A 5.13; p = 0.87.
Read it. Check the manipulation, then the balance (only pre-treatment variables), then the effect. The “link” version did not raise support (−0.19 points). With 8 and 12 readers the test has very little power: a null result from a weak test is weak evidence of no effect.
scatter support pater
regress support pater
regress support game_hours
regress support gamer_d
regress support gamer_d female
regress support gamer_d female pater
regress support gamer_d female pater harmful
What you should see.
| Model | gamer_d | female | pater | harmful | R² |
|---|---|---|---|---|---|
pater only |
0.279 | 0.047 | |||
| (1) | −3.765* | 0.278 | |||
| (2) | −3.373* | 1.537 | 0.364 | ||
| (3) | −3.701* | 1.374 | 0.348 | 0.435 | |
| (4) | −3.948* | 1.414 | 0.337 | −0.851 | 0.460 |
game_hours: −0.077** (R² = 0.374).
Read it. H2: paternalism goes in the predicted direction but is far from significant. H1 with another measure: each extra hour of gaming per week goes with 0.08 points less support. H4: the gamer coefficient stays around −3.4 to −3.9 when gender, paternalism and the article are held constant. Model (1) gives the same difference as the t-test: a regression on a dummy is a t-test. With 20 students and 3 gamers, read all of this as a lesson in method, not as a finding.
lr) to model (4). What happens to
gamer_d, and to the number of observations? Why?regress support gamer_d female pater harmful lr
ttest support, by(italy)
regress drops every row with a
missing value. gamer_d (−4.06) loses its star: fewer cases,
less power.Lecture 13.3 put the tools together. Two things worth practising:
use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/chile1988.dta", clear
* frequency distribution of a nominal variable
tab1 vote
* percentages within each region (X in the rows)
tab2 region vote, row
* a dummy: recode with ranges
recode age (18/64 = 0) (65/99 = 1), generate(old)
label define oldlab 0 "Under 65" 1 "65 or more"
label values old oldlab
tab1 old
* compare the means of an interval variable between two groups
ttest statusquo, by(sex)
use "https://raw.githubusercontent.com/francescovisconti/MSR-data/main/worldcup_democracy.dta", clear
ttest polyarchy, by(finalist)
regress goals polyarchy
regress goals polyarchy host gdppc
What you should see. “Will vote Yes”: 46.91% in the
Metropolitan area, 27.64% in the City of Santiago. 183 respondents aged
65 or more. statusquo: women 0.066, men −0.068, p = 0.0005.
regress goals polyarchy: 2.571***, R² = 0.028; with
host and gdppc: polyarchy 2.890***, host
4.187***, gdppc −0.014 (no star), R² = 0.067.
Read it. Back to week 8 with the tools of weeks 12 and 13: from full autocracy to full democracy, about 2.6 to 2.9 more goals per tournament, holding hosting and wealth constant. Can we say that democracy causes better performance? No: polyarchy is not randomly assigned, controls work only for what we measured (football tradition is not in the data), and only teams that qualified are in the dataset.
DAX translates Stata-style commands into R. Most of what you need works, but a few things do not, and some outputs look different from desktop Stata.
| Works | Notes |
|---|---|
use "https://…/file.dta", clear |
load data from a web address |
describe, browse |
in some versions browse only says “acknowledged”: use
the View Data button |
summarize x y z |
always list the variables; shows the median; , detail
adds nothing |
summarize x if g == 1 |
if works with summarize,
scatter and correlate |
by g: summarize x |
summary statistics within groups (use by, not
bysort) |
tab1 x, tab2 x y, row col |
frequency and contingency tables; tab1 shows Valid
percent and Percent |
generate |
arithmetic and functions: x / 10, a + b,
log() |
recode x (1/3 = 0) (4/5 = 1), generate(y) |
categories and dummies; copies the old labels, so define new ones |
label define, label values,
label variable |
|
ttest y, by(g), ttest y = 4 |
Welch test; prints the two means, t (df) and the two-sided p only |
correlate x y z, scatter y x |
the first variable of scatter goes on the vertical
axis |
histogram x |
one bar per distinct value; options such as bin(),
discrete, percent are ignored |
regress y x1 x2, regress y i.g |
coefficient, (SE) and stars; i. uses the lowest code as
reference |
| Does not work | Do this instead |
|---|---|
generate y = x if … |
build the variable for everyone with recode |
dummies with comparisons,
e.g. generate d = (x > 10) |
gives TRUE/FALSE and labels do not apply: use
recode |
recode x (else = …) or
recode x (… = .) |
list every value or range explicitly |
ttest … if …, regress … if … |
summarize … if, or build a group variable and use
by() |
bysort g:, egen |
by g: summarize |
ib5.x (another reference category) |
recode so that the reference gets the lowest code, then
i.x |
tabstat, codebook, collapse,
preserve, predict |
summarize, tab1; type predicted values
with generate |
| comments after a command on the same line | put every comment on its own line |
log, cd, pwd,
clear all |
not needed: load data from the web |
Reading DAX output.
summarize rounds to two decimals: if you need more
precision, rescale the variable first (e.g. multiply a proportion by
100).ttest y, by(g) computes group 0 − group
1 (lower code minus higher code): check which group is which
before you write the sign. Difference = mean 1 − mean 2, SE = difference
/ t, 95% CI ≈ difference ± 2 × SE. A p-value printed as 0
means p < 0.0001.regress prints neither t nor the exact p: t =
coefficient / SE, and the stars give the p (* < 0.05, ** < 0.01,
*** < 0.001). If a standard error reads 0.001 or 0.000, rescale the
variable before computing t.tab1 and define new labels.col into column and
the command fails, click Run instead of pressing
Enter.The point of this part of the course is not to learn a software package. It is to learn how to move from a research question to a defensible empirical analysis:
Textbooks
Studies used in the examples
Data sources
ches2024_lab is a teaching extract.gss2021_lab and
gss2021_marital are teaching extracts (complete cases,
unweighted).resume, minwage,
face, vignettes, turnout,
afghan and afghan_village come from Imai &
Bougher (2021); polarization is derived from their
congress and USGini files;
battery uses items from the International Personality Item
Pool. msr_survey_games is the anonymous class survey of MSR
2026/27 (Channel B).