How to use this tutorial

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 idea: the point of the lecture, in a few lines.
  • Code blocks you can copy with one click and paste into DAX.
  • What you should see: the key numbers, to check that your output is right.
  • Read it: how to interpret the output.
  • Try it yourself: short exercises, with solutions you can open after you have tried.

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.

Getting started in DAX

  1. Go to dax.luiss.it and sign in with your DAX account (the email and password you chose when you signed up to DAX, not your Luiss credentials).
  2. Click New Session.
  3. Load a dataset directly from the course data folder with 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
  1. Type one command at a time in the command box and click Run, or write a sequence in the Script editor and run it line by line (Ctrl/Cmd + Enter).

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.

The datasets

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)

Week 8 · How science works

The idea

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

Open the data and look around

Block 1 - first look
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.

Describe one variable at a time

Block 2 - X and Y
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.

Operationalisation, in code

Block 3 - from a score to a typology
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.

Test the hypothesis

Block 4 - a first test
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.

  • The scatter rises over time because the world became more democratic. Two variables that both trend over time will correlate whether or not they are related.
  • 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.
  • Champions are more democratic, but with only 23 champions the difference is not significant. Finalists (46) show the same difference, and with twice the cases it is significant: that is statistical power.
  • Even a significant difference is an association: richer countries are both more democratic and better at football.

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.

Try it yourself

  1. Do hosts score more goals than everybody else? Is that a causal effect of hosting?
  2. How closely do polyarchy and polity2 agree?
  3. Build a democracy dummy from polity2 (6 or more = democracy) and cross it with winner.
Show solutions
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.


Week 9 · Concepts, variables and measurement

The idea

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.

DAX will compute anything

Block 1 - a nominal variable
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.

The alphabetical trap

Block 2 - put the categories in order
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.

Going down a level, and dummies

Block 3 - age groups and a dummy
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.

Measurement error: is the survey valid?

turnout.dta compares the turnout reported in the American National Election Studies (ANES) with official turnout in 14 US elections.

Block 4 - a reliable but invalid instrument
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.

Known-groups validity

If statusquo (an index of support for the regime) is valid, declared Yes voters should score much higher than declared No voters.

Block 5 - does statusquo measure support?
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.


Week 9 · Describing one variable

The idea

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.

Frequency distributions: percent of what?

Block 1 - frequency tables and histograms
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.

Centre and shape

Block 2 - mean, median and shape
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.

  • Income is strongly right-skewed: a few high incomes pull the mean far above the median. For a distribution like this, report the median.
  • statusquo has two humps: opponents and supporters of the regime, few in between. A mean of 0 describes almost nobody.
  • In DAX summarize already shows the median (last column). summarize, detail adds nothing, and DAX does not compute skewness: compare mean and median, then plot.

Spread

Block 3 - range, IQR, standard deviation
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.

Try it yourself

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?

Show solution
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.


Week 10 · Asking questions

The idea

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.

Do the categories mean the same thing to everyone?

Block 1 - anchoring vignettes
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.

Missing answers

afghan.dta: 2,754 civilians interviewed in 2011 in five Afghan provinces.

Block 2 - who did not answer?
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.

A question nobody can safely answer: the list experiment

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

Block 3 - the list experiment
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.


Week 10 · Scales

The idea

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

Does anything look odd?

Block 1 - first look
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.

Reverse, check, build

Block 2 - reverse coding and the scale
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.

  • Reversed value = (min + max) − original = 7 − a1.
  • Cronbach’s alpha from the average correlation: α = n·r̄ / [1 + r̄(n − 1)] = 5 × 0.3325 / (1 + 0.3325 × 4) = 0.71, just above the conventional threshold of 0.70. Before reversing a1 it was 0.46.
  • The mean below the median signals a long left tail: most people describe themselves as agreeable (social desirability may help).
  • Alpha measures reliability, not validity.

Week 10 · Sampling

The idea

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.

Sampling error, seen with your own eyes

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%.

Block 1 - 500 samples
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.

Was the multistage sample representative?

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.

Block 2 - were the surveyed villages typical?
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.

Try it yourself (preparation for the lab)

  1. Recode 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?
  2. Summarize altitude and population separately for sampled and non-sampled villages. Why do the mean populations differ more than the medians?
Show solutions
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
  1. High villages are 46.51% of the non-sampled and 47.55% of the sampled villages: almost the same, as we expect from a random selection.
  2. Mean population 754 vs 680, but medians 450 vs 453. The largest non-sampled village has 35,900 people, the largest sampled one 6,509: a few very large villages pull up the mean, not the median. In DAX use by group:, not bysort group:.

Week 11 · The DAX lab

The idea

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.

The two exercises

Lab - Euroscepticism and the radical right
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.

  • One row is one party; family is nominal, vote is a ratio variable.
  • The median below the mean: most parties are pro-EU, and a smaller group of strongly Eurosceptic parties pulls the mean up (right skew).
  • Radical-right parties are 2.88 points more Eurosceptic on the 1–7 scale, but on average they are not bigger: they differ on Europe, not in size.

Week 11 · Causality and experiments

The idea

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.

A field experiment on hiring discrimination

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.

Block 1 - did the name change the callback rate?
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.

  • A gap of 3.2 percentage points; in relative terms 9.65 / 6.45 = 1.50: white names get 50% more callbacks.
  • The mean of a 0/1 variable is a proportion, so ttest compares two callback rates.
  • It is a causal effect of the name because names were assigned at random, and the balance check shows the groups are alike.
  • With the treatment in the rows, use row percentages.

Is the gap the same for women and men?

Block 2 - four groups
* 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.)


Week 12 · Observational studies and bivariate relationships

The idea

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.

A minimum-wage law

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.

Block 1 - an observational study
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.)

Contingency tables

gss2021_lab.dta: 3,500 American adults. gunlaw: should a police permit be required before buying a gun? (1 favor, 2 oppose).

Block 2 - percentages in the right direction
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.

Scatterplot and correlation

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.

Block 3 - inequality and polarization
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.

Try it yourself

  1. How are the positions of the median Republican and the median Democrat related?
  2. Do men and women differ on the death penalty (cappun: 1 favor, 2 oppose)?
Show solutions
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
  1. r = −0.65: as Republicans moved right, Democrats moved left.
  2. In favour: men 59.30%, women 53.16%, a gap of about 6 points.

Week 12 · Linear regression

The idea

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 + ε

  • α (intercept): the predicted Y when X = 0.
  • β (slope): the expected change in Y for a one-unit increase in X.
  • The residual of each case is observed Y minus predicted Y. Least squares chooses the line that makes the squared residuals as small as possible.

Can a face predict an election?

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.

Block 1 - build the outcome, look, measure
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.
  • Slope: 10 more points of participants finding the Democrat more competent go with a margin about 6.6 points larger (0.1 × 0.660).
  • Intercept: the predicted margin when nobody finds the Democrat more competent (−31 points): an extrapolation, few races are near 0.
  • R² = 0.187: the faces account for about 19% of the variation in the margin; 81% is left in the residuals. With one predictor R² = r² (0.433² = 0.187).
  • DAX shows standard errors in parentheses and stars for significance (*** p < 0.001). Order matters: regress d_comp diff_share gives a different slope (0.284) but the same R².

Predicted values and residuals

DAX has no predict: type the coefficients yourself.

Block 2 - prediction by hand
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.


Week 12 · Multiple regression and categorical predictors

The idea

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

Holding the others constant

Block 1 - from one predictor to three
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.

Categorical predictors

Block 2 - the wrong way and the right way
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.

Block 3 - changing the reference category
* 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.

Everything together, and R²

Block 4 - the full model
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.

Try it yourself

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.

Show solution

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.


Week 13 · Hypothesis tests and p-values

The idea

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.

  1. State the null hypothesis H0 (no difference, no effect) and the alternative H1.
  2. Fix the significance level α in advance, usually 0.05.
  3. Compute the test statistic: t = (estimate − value under H0) / standard error. Signal divided by noise.
  4. Find the p-value: the probability of a result at least as extreme as ours, if H0 were true.
  5. Decide (p ≤ α: reject H0; p > α: fail to reject), then ask how big the difference is.

A difference between two groups

Block 1 - are American women more liberal than men?
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:

  • difference = 4.0573 − 3.8741 = 0.183;
  • standard error = difference / t = 0.183 / 3.498 = 0.052;
  • 95% confidence interval ≈ 0.183 ± 2 × 0.052 = [0.08, 0.29]: zero is not inside, same conclusion as p < 0.05.

p = 0.0005 < 0.05: we reject H0. Women place themselves slightly to the left of men: significant, but small (3% of the scale).

One mean against a fixed value

Block 2 - is the average American a moderate?
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.

Every regression coefficient is a test

Block 3 - stars and t by hand
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.

  • For every coefficient H0 is β = 0. DAX prints the coefficient, the standard error in parentheses and stars: * p < 0.05, ** p < 0.01, *** p < 0.001, no star p ≥ 0.05. Compute t by hand: 0.155 / 0.009 ≈ 17.
  • 95% confidence interval ≈ coefficient ± 2 × SE: it excludes 0 exactly when p < 0.05.
  • A regression on a dummy is a t-test: the constant (4.057) is the mean of men, the coefficient (−0.183) is women minus men, the same difference as Block 1.
Block 4 - a rounding trap
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.

  • Not the probability that H0 is true: it is computed assuming H0 is true.
  • Not a measure of size: with a huge sample a tiny effect can have p = 0.001.
  • “Not significant” is not “no effect”: small samples miss real effects.
  • Not proof of causation: a test rules out chance, not confounding.

Try it yourself

  1. Do supporters and opponents of the death penalty (cappun) differ in ideology? Do supporters and opponents of gun permits (gunlaw) differ in religious attendance?
  2. In regress polviews i.degree, which degree groups differ significantly from the reference (less than high school)?
Show solutions
ttest polviews, by(cappun)
ttest attend, by(gunlaw)
  1. Death penalty: 4.44 vs 3.34, a difference of 1.09 points, t = 22.2, p printed as 0 (read: p < 0.0001): large and clear. Gun permits: 2.76 vs 2.95, t = −1.82, p = 0.069: we fail to reject at 5%.
  2. Bachelor’s (−0.408**) and graduate (−0.690***) are more liberal than people without a high-school diploma; high school (+0.028) and junior college (+0.072) do not differ significantly (no stars).

Week 13 · Our class survey: video games and politics

The idea

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?

  • Y = support: mean of two proposals (sup_ban, no violent games to under-18s; sup_limit, a 2-hour daily limit), 0 oppose … 10 support.
  • H1 (experience): gamers support the restrictions less (gamer_d, game_hours).
  • H2 (values): more paternalism, more support (pater, 0–10).
  • H3 (evidence): an experiment. Half of you read an article saying research finds a link between violent games and aggression (A), half an article saying it does not (B): harmful.
  • H4: the gamer gap holds with controls.

msr_survey_games.dta: 20 questionnaires analysed (1 excluded for failing the attention check).

Look first, then a table

Block 1 - who are we?
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.

H1: a t-test

Block 2 - gamers and the others
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.

H3: the experiment

Block 3 - manipulation check, balance, effect
* (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.

H2 and H4: regression

Block 4 - simple and multiple regression
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.

Try it yourself

  1. Add left-right (lr) to model (4). What happens to gamer_d, and to the number of observations? Why?
  2. Do students who grew up in Italy support the restrictions more than international students? Write one sentence with direction, size, test and design.
Show solutions
regress support gamer_d female pater harmful lr
ttest support, by(italy)
  1. n falls from 20 to 15: five students did not place themselves on the left-right scale, and regress drops every row with a missing value. gamer_d (−4.06) loses its star: fewer cases, less power.
  2. International students 5.95, students who grew up in Italy 4.45: “In our class (n = 20), students who grew up in Italy supported the restrictions 1.5 points less than international students, but the difference is not significant (t = 1.30, p = 0.21). Where you grew up was not assigned at random: at most an association.”

Week 13 · Review for the midterm

Lecture 13.3 put the tools together. Two things worth practising:

Review - which command?
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 survival kit

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.
  • When you create a variable from another one, DAX may copy its value labels: always check with tab1 and define new labels.
  • If autocomplete turns col into column and the command fails, click Run instead of pressing Enter.

Final note

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:

  1. Formulate a question that could be answered wrong.
  2. Turn concepts into variables, and make every decision explicit.
  3. Look at the data before you test anything.
  4. Describe one variable at a time, then relationships.
  5. Ask what the comparison assumes: is the counterfactual credible?
  6. Report size and uncertainty, not just stars: “significant” is not “important”.
  7. Association is not causation unless the design says so.
  8. Keep everything in a script, so that anyone can re-run it.

References

Textbooks

  • Corbetta, P. (2003). Social Research: Theory, Methods and Techniques. London: SAGE. https://doi.org/10.4135/9781849209922
  • Imai, K., & Bougher, L. D. (2021). Quantitative Social Science: An Introduction in Stata. Princeton, NJ: Princeton University Press. ISBN 978-0-691-19109-6.

Studies used in the examples

  • Bertrand, M., & Mullainathan, S. (2004). Are Emily and Greg more employable than Lakisha and Jamal? A field experiment on labor market discrimination. American Economic Review, 94(4), 991–1013. https://doi.org/10.1257/0002828042002561
  • Card, D., & Krueger, A. B. (1994). Minimum wages and employment: A case study of the fast-food industry in New Jersey and Pennsylvania. American Economic Review, 84(4), 772–793. Author’s copy: https://davidcard.berkeley.edu/papers/min-wage-ff-nj.pdf
  • King, G., Murray, C. J. L., Salomon, J. A., & Tandon, A. (2004). Enhancing the validity and cross-cultural comparability of measurement in survey research. American Political Science Review, 98(1), 191–207. https://doi.org/10.1017/S000305540400108X
  • Lyall, J., Blair, G., & Imai, K. (2013). Explaining support for combatants during wartime: A survey experiment in Afghanistan. American Political Science Review, 107(4), 679–705. https://doi.org/10.1017/S0003055413000403
  • Todorov, A., Mandisodza, A. N., Goren, A., & Hall, C. C. (2005). Inferences of competence from faces predict election outcomes. Science, 308(5728), 1623–1626. https://doi.org/10.1126/science.1110589

Data sources

  • Coppedge, M., et al. (2024). V-Dem Codebook v14. Varieties of Democracy (V-Dem) Project. https://www.v-dem.net/data/the-v-dem-dataset/
  • Fox, J., Weisberg, S., & Price, B. carData: Companion to Applied Regression Data Sets (R package; source of the Chile 1988 survey). https://cran.r-project.org/package=carData
  • Chapel Hill Expert Survey (CHES), 2024 wave. https://www.chesdata.eu. ches2024_lab is a teaching extract.
  • Marshall, M. G., & Gurr, T. R. (2020). Polity5: Political Regime Characteristics and Transitions, 1800–2018. Center for Systemic Peace. https://www.systemicpeace.org/inscr/p5manualv2018.pdf
  • NORC at the University of Chicago. General Social Survey 2021. https://gss.norc.org. gss2021_lab and gss2021_marital are teaching extracts (complete cases, unweighted).
  • The World Cup data were compiled for this course from FIFA records, V-Dem and Polity5. 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).