Week 4 · Probabilities and tests for categorical variables

counting instead of measuring

The moth knew every burrow in the wood where a screen was still glowing at night, and in many of those burrows someone lay tossing and turning.

“Phone by the bed, bad sleep,” he said, “always together.”

“Together that often,” said the bat, “it can’t be anything else: it means something.”

The dormouse turned over, towards the side of the wood where the burrows were dark.

“And over there,” she asked, “where the phone stays out in the hall: how do they sleep there?”

The moth didn’t know: he had never looked inside a dark burrow.

What you learn this week

  • counting instead of measuring: categorical variables in a contingency table
  • three probabilities from one table: marginal, joint and conditional
  • using conditional probabilities to see whether there is an association in your group, and when two variables are independent
  • the same question with the multiplication rule
  • the expected counts when nothing is going on
  • the χ² test of independence, by hand and in R
  • why χ² has one tail and still doesn’t pick a side
  • what to do with the correction that R adds without being asked

Counting instead of measuring

Remember? Statistics has no other goal than to predict and explain differences, in the population. This week you link differences in sleep, good or poor, to where the phone is at night.

So far, every measurement had a number on a scale: a worry score, an age, how long someone sleeps. You can work out a mean of that. But a lot of what you want to know in psychology is a category. Do you sleep poorly or well? Is your phone next to your bed at night, or out in the hall? A variable like that is called categorical (nominal or ordinal), and it has no mean. What you can do: count how often each combination occurs.

The question is still the one from week 1, in different clothes:

Are two categorical variables related in the population, or do you happen to see a pattern in your sample by chance?

For that you need two things this week: a bit of probability theory, and one test, the χ² test (chi-square).

You build it up calmly, with one table that stays the same all week. First you take probabilities from it. Then you use those probabilities to see whether there is an association in your group at all. And only after that comes the test.

Probabilities from a contingency table

The contingency table

A researcher asks 100 first-year students two things: where is your phone at night, and how do you usually sleep? Two categorical variables, phone location and sleep, each with two categories. Set them out against each other and you get a contingency table:

Phone location and sleep for 100 first-year students
phone sleeps poorly sleeps well total
in the bedroom 30 30 60
elsewhere 10 30 40
total 40 60 100

Read it first, without working anything out yet. Inside are four cells. Each cell counts the people who meet two conditions at once: top left are the 30 students who have their phone in the bedroom and sleep poorly.

Along the edge are the marginal totals. On the right, the row totals: 60 people have their phone in the bedroom, 40 have it elsewhere. At the bottom, the column totals: 40 sleep poorly, 60 sleep well. And in the bottom-right corner, where the total row and the total column cross, is everyone: N=100N = 100. The row totals add up to NN, and so do the column totals.

The marginal probability: from the edge

Every probability you take from a table like this is a fraction. Think of a lucky-dip barrel. Below the fraction line is the barrel: everyone you draw from. Above the line are the hits: the ones in it who match what you are asking about.

With each fraction below, the table appears too, and every number from the fraction sits in it in the same box: hit row total column total grand total N. That way you can see where every number comes from.

The marginal probability is about one variable. Draw one student at random from all 100. What is the probability that they sleep poorly?

phonesleeps poorlysleeps welltotal
in the bedroom303060
elsewhere103040
total4060100
P(poor sleep)=40100=.40
  • the barrel is everyone (double border): the whole table is in it
  • 40 above the line: everyone in the column sleeps poorly
  • 100 below the line: everyone, the whole barrel

It is called marginal because you take it from the margin: the edge of the table, where the marginal totals are. The 40 is at the bottom, in the total row. Where the phone is plays no part: you fold that variable away for a moment. In the same way, P(bedroom)=60100=.60P(\text{bedroom}) = \dfrac{60}{100} = .60, with the row total on the right.

The joint probability: from one cell

The joint probability is about two things at once. What is the probability that this one student has their phone in the bedroom and sleeps poorly? The barrel is still everyone; the hits are the ones who meet both conditions. That is one cell:

phonesleeps poorlysleeps welltotal
in the bedroom303060
elsewhere103040
total4060100
P(bedroom and poor sleep)=30100=.30
  • the barrel is everyone (double border): the whole table is in it
  • 30 above the line: the cell in the bedroom, sleeps poorly
  • 100 below the line: everyone, the whole barrel

Look where the box above the line is now. You take the marginal probability from the edge, from a total. You take the joint probability from inside the table, from one cell: you simply read it off.

Besides and, there is or. With or you may think: at least one of the two. The phone is in the bedroom, or you sleep poorly, or both. That is different from ordering at a snack bar: fries or a burger? Then you pick one. In statistics, it may be both.

P(A or B)=P(A)+P(B)−P(A and B) P(A \text{ or } B) = P(A) + P(B) - P(A \text{ and } B)

You subtract that last term so that you don’t count the overlap twice. In the table:

P(bedroom or poor sleep)=.60+.40−.30=.70 P(\text{bedroom or poor sleep}) = .60 + .40 - .30 = .70

Count it yourself: 30 + 30 + 10 = 70 people have their phone in the bedroom, sleep poorly, or both. Only the 30 in the cell elsewhere, sleeps well are left out.

phonesleeps poorlysleeps welltotal
in the bedroom303060
elsewhere103040
total4060100
P(bedroom or poor sleep)=30+30+10100=70100=.70
  • the barrel is everyone (double border): the whole table is in it
  • 30 above the line: the cell in the bedroom, sleeps poorly
  • 30 above the line: the cell in the bedroom, sleeps well
  • 10 above the line: the cell elsewhere, sleeps poorly
  • 100 below the line: everyone, the whole barrel

Leave out the minus, and you get .60+.40=1.00.60 + .40 = 1.00, and that is too much. The top-left cell, bedroom and poor sleep, is in both probabilities, so you count it twice. Take it off once: 1.00−.30=.701.00 - .30 = .70.

If two events don’t overlap, they are called disjoint. Sleeping poorly with the phone in the bedroom, and sleeping poorly with the phone elsewhere: both at once is impossible. The probability of both is then zero, the minus drops out, and you may simply add: .30+.10=.40.30 + .10 = .40, the probability of poor sleep. So it is still one rule.

The conditional probability: a smaller barrel

The conditional probability changes the barrel. What is the probability of sleeping poorly, given that the phone is in the bedroom? Now you only draw from the 60 people with their phone in the bedroom. That is your new barrel, and it goes below the line:

phonesleeps poorlysleeps welltotal
in the bedroom303060
elsewhere103040
total4060100
P(poor sleep∣bedroom)=3060=.50
  • the barrel (solid border, also under the words in the fraction): only the row in the bedroom is still in it
  • 30 above the line: the cell in the bedroom, sleeps poorly
  • 60 below the line: everyone in the row in the bedroom, the whole barrel
  • light numbers, outside the border of the barrel: not in it

The same 30 above the line as in the joint probability, but the barrel below it is smaller: 60 instead of 100.

You read the vertical bar ∣\mid as given that: what comes after it is the condition, and the condition decides the barrel.

Now the other row. Given that the phone is elsewhere, the barrel is the group of 40 people with their phone elsewhere:

phonesleeps poorlysleeps welltotal
in the bedroom303060
elsewhere103040
total4060100
P(poor sleep∣elsewhere)=1040=.25
  • the barrel (solid border, also under the words in the fraction): only the row elsewhere is still in it
  • 10 above the line: the cell elsewhere, sleeps poorly
  • 40 below the line: everyone in the row elsewhere, the whole barrel
  • light numbers, outside the border of the barrel: not in it

Two rows, so two barrels, and two probabilities of sleeping poorly: with the phone in the bedroom .50, with the phone elsewhere only .25.

WarningThe order matters

P(poor sleep∣bedroom)P(\text{poor sleep} \mid \text{bedroom}) is not the same as P(bedroom∣poor sleep)P(\text{bedroom} \mid \text{poor sleep}). In the second one, the barrel is the 40 poor sleepers, and 30 of them have their phone in the bedroom:

phonesleeps poorlysleeps welltotal
in the bedroom303060
elsewhere103040
total4060100
P(bedroom∣poor sleep)=3040=.75
  • the barrel (dashed border, also under the words in the fraction): only the column sleeps poorly is still in it
  • 30 above the line: the cell in the bedroom, sleeps poorly
  • 40 below the line: everyone in the column sleeps poorly, the whole barrel
  • light numbers, outside the border of the barrel: not in it

The same 30 above the line, but below it there is now a column instead of a row. A different number, because a different barrel.

The p-value from week 1 is a conditional probability too: the probability of a bike given that the shop is a bakery. Not the probability that it is a bakery, given a bike.

Is there an association at all?

Now the question that this week is about: are phone location and sleep related? You don’t need a test for that yet. First you simply look at your table, with the two conditional probabilities from just now.

Two variables are independent if one tells you nothing about the other. You know where someone’s phone is at night, and that changes nothing about your guess of how they sleep? Then they are independent. Two rules of thumb go with that, and they say the same thing:

  1. The conditional probabilities are equal in all groups. The probability of sleeping poorly is just as big with the phone in the bedroom as without.
  2. The conditional probabilities are equal to the marginal probability. In each group, the same share sleeps poorly as in the whole table.

Put the two conditional probabilities side by side, with the marginal probability below them:

  • P(poor sleep∣bedroom)=3060=.50P(\text{poor sleep} \mid \text{bedroom}) = \dfrac{30}{60} = .50
  • P(poor sleep∣elsewhere)=1040=.25P(\text{poor sleep} \mid \text{elsewhere}) = \dfrac{10}{40} = .25
  • P(poor sleep)=.40P(\text{poor sleep}) = .40

Not equal. So in this group of 100, phone location and sleep are related: people with their phone in the bedroom sleep poorly more often.

The .40 of everyone lies between the two, because it counts both groups together: 30+10=4030 + 10 = 40 poor sleepers out of 100. If the two conditional probabilities are equal, say 24 out of 60 and 16 out of 40, the .40 is too: 24+16=4024 + 16 = 40. That is how the hollow bars stand on the right in Figure 1. That is why the two rules of thumb say the same thing.

You can also compare within the columns instead of the rows. Then the barrel is a column, as in the box The order matters:

  • P(bedroom∣poor sleep)=3040=.75P(\text{bedroom} \mid \text{poor sleep}) = \dfrac{30}{40} = .75
  • P(bedroom∣good sleep)=3060=.50P(\text{bedroom} \mid \text{good sleep}) = \dfrac{30}{60} = .50
  • P(bedroom)=.60P(\text{bedroom}) = .60

Not equal either: .75 against .50. Rows or columns: you always reach the same verdict.

Careful: the second line has, just like P(poor sleep∣bedroom)P(\text{poor sleep} \mid \text{bedroom}), 30 above the line and 60 below it. Still, it is something else: above the line the cell bedroom, sleeps well, and below it the column sleeps well instead of the row in the bedroom.

Had the probabilities been equal, there would have been no association to see, and you would be done here. Since they differ, you do see an association in this group. Is it there among all first-year students too? Maybe. That is what the rest of the week is about.

In this group, or in the population?

Look closely at what you just did. You looked at these 100 first-year students, and saw a difference: .50 against .25. For this group, that is a fact. But almost every sample shows some difference, even when the two variables are completely independent in the population. Just as in week 1, where a sample mean almost never came out at exactly 50.

TipTwo questions that look alike
  • “Are the variables dependent in this group?” Look only at the probabilities in the table. If the conditional probabilities are equal, then: independent. If they differ at all, however little, then: dependent, in this group. No test needed. Always work them out. With real data they almost never come out exactly equal, but in exercises and exam questions they often do. Two pairs of bars show it as well, in Figure 1: the same height, or not.

    Two bar charts side by side, each with its own axis on the same scale, from .00 to .60; on the left that axis is called 'probability of sleeping poorly'. On the left, titled 'as it is in these 100 students: not equal, so dependent': two filled blue bars, 'phone in the bedroom (60)' .50 and 'phone elsewhere (40)' .25, each with that probability above it; the bedroom bar is twice as tall as the other one, and one and a half times as wide, because each bar is as wide as its group. On the right, titled 'if the phone made no difference: equal, so independent': the same two bars hollow, outlined only, exactly the same height, both .40. A grey dashed line at .40 runs through both panels, labelled in the right margin as 'everyone together: 40 of 100 = .40'. On the right both bars end exactly on that line; on the left the bedroom bar sticks out above it and the other one stays below it.
    Figure 1: Left: the phone table from this week, .50 against .25. Right: no new data but a thought experiment, hence the hollow bars: the same 100 first-year students, as the table would look if phone location made no difference. Each bar is as wide as its group. The line is the probability for everyone together, 40 of the 100. On the right, exactly that share sleeps poorly in each group, so the bars end on it; on the left the line lies closer to .50 than to .25, because the wide bar counts for more.

    How to read it: on the left, the height of the wide bar is the probability of sleeping poorly when your phone is in the bedroom (.50). The bar next to it is half as tall (.25): people who keep their phone elsewhere sleep poorly less often, so dependent, in this group. On the right the two bars are the same height, both .40: that is what independent looks like, and then phone location tells you nothing about your sleep.

  • “Are they related in the population?” or “Is the association significant?” Dependent in this group says nothing about that yet. The question then is whether the difference is bigger than chance can make it. The χ² test decides that.

The multiplication rule: the same question, from the other side

You can also ask the same question from the other side: not with a probability within one group, but with the joint probability from one cell.

When you see and, you quickly think of times. That’s allowed, but only with independence. You also meet this rule as the multiplicative law for independent events, or the product rule for short:

NoteMultiplication rule — only for independent variables

P(A and B)=P(A)×P(B) P(A \text{ and } B) = P(A) \times P(B)

Here, independent variables are two variables that tell you nothing about each other, and dependent means dependent on each other. That is not the same as the independent and the dependent variable of a study; see Three uses of independent in week 3.

Try it on the table: P(bedroom)×P(poor sleep)=.60×.40=.24P(\text{bedroom}) \times P(\text{poor sleep}) = .60 \times .40 = .24. But in the table, the joint probability is .30. The rule gives the wrong number, and that is exactly the sign that the two variables are not independent.

Why does a wrong number say dependent? You didn’t work out that .30 with a rule: you read it off the table, 30 out of 100. Reading off always works, and what you read off is right. The rule is only allowed when the two variables are independent. Here it doesn’t give what you read off. So it wasn’t allowed here: the variables are dependent. That is why you always read off first.

The rule you may always use, the general multiplicative law, is almost the same: a conditional probability takes the place of P(B)P(B).

NoteMultiplication rule — always

P(A and B)=P(A)×P(B∣A) P(A \text{ and } B) = P(A) \times P(B \mid A)

P(bedroom)×P(poor sleep∣bedroom)=.60×.50=.30P(\text{bedroom}) \times P(\text{poor sleep} \mid \text{bedroom}) = .60 \times .50 = .30. That one does work.

Put the two calculations side by side: .60×.50=.30.60 \times .50 = .30 against .60×.40=.24.60 \times .40 = .24. The only difference is .50 against .40: the conditional probability against the marginal one. You already put those two side by side in Is there an association at all? So the multiplication rule asks the same question, from the other side, and reaches the same answer: dependent, in this group.

If AA and BB are independent, then P(B∣A)P(B \mid A) is simply P(B)P(B), and the rule becomes P(A)×P(B)P(A) \times P(B). So you may always calculate with the general rule. But because it always works, you can’t check anything with it: it also works when the variables are related. If you want to know whether they are independent, compare the rule for independent variables, P(A)×P(B)P(A) \times P(B), with what you read off.

Still, you don’t throw that .24 away. It is exactly the joint probability you would expect if nothing were going on, and that is where the next step begins.

What you expect when nothing is going on

Every test calculates from H0H_0: pretend nothing is going on, and see how strange your data are then. Here H0H_0 says: phone location and sleep are independent. Which counts should the table have in that case?

Reason it out first. In the whole group, the proportion of poor sleepers is .40. If the two variables are independent, then in each group the proportion of poor sleepers is that same .40: those are the hollow bars of Figure 1. Of the 60 people with their phone in the bedroom, you therefore expect .40×60=24.40 \times 60 = 24.

That is the multiplication rule for independent variables, times the number of people: 100×.60×.40=24100 \times .60 \times .40 = 24. The probability .60×.40=.24.60 \times .40 = .24 was the wrong number a moment ago: the table said .30. Here the rule is allowed. You are not working out what you actually counted, but what you would count if H0H_0 were true, and H0H_0 says precisely that the two variables are independent.

With the rule you may always use, you would only get back what you actually counted (100×.60×.50=30100 \times .60 \times .50 = 30), and the same in every cell of every table.

Write the two probabilities as fractions over the grand total NN, and one NN cancels out:

100×60100×40100=60×40100=24 100 \times \dfrac{60}{100} \times \dfrac{40}{100} = \dfrac{60 \times 40}{100} = 24

Row total times column total, divided by the grand total. That is the short formula:

NoteThe expected count in a cell

fe=row total×column totalN f_\text{e} = \dfrac{\text{row total} \times \text{column total}}{N}

  • fef_\text{e}: the expected count in a cell, if H0H_0 is true
  • fof_\text{o}: the observed count, the one you actually counted

You also meet them as expected and observed frequency, per cell as cell frequency, or for short as EE and OO. A frequency is just a count.

The movement for each cell: look sideways to the row total, down to the column total, multiply, and divide by NN. For the cell bedroom, poor sleep. There are no hits in the fraction now, only totals:

phonesleeps poorlysleeps welltotal
in the bedroomcounted303060
elsewhere103040
total4060100
fe=row total×column totalN=60×40100=2400100=24
  • 60 the row total: everyone in the row in the bedroom
  • 40 the column total: everyone in the column sleeps poorly
  • 100 the grand total N: everyone
  • the cell you work out fe for; you counted 30 there, and you do not need that number for fe
  • light numbers without a box: not in the sum

And the same for all four:

The expected counts if phone location and sleep are independent
sleeps poorly sleeps well total
in the bedroom 60×40100=24\dfrac{60 \times 40}{100} = 24 60×60100=36\dfrac{60 \times 60}{100} = 36 60
elsewhere 40×40100=16\dfrac{40 \times 40}{100} = 16 40×60100=24\dfrac{40 \times 60}{100} = 24 40
total 40 60 100

Two things to see. The expected counts have the same totals in the margins (the marginal totals) as the real table; count it yourself. And in a two-by-two table you only need to work out one of them: once the totals are fixed, the other three follow by subtraction (60 − 24 = 36, and so on).

Those expected counts are the most informative part of the whole test. Put them next to what you counted: 30 poor sleepers with their phone in the bedroom, where you expected 24. That’s where the story is.

The χ² test: how far apart are counted and expected?

Only now the test. In this group you saw an association: .50 against .25, and 30 poor sleepers with their phone in the bedroom where you expected 24. But even in a world without an association, a table almost never comes out at exactly its expected counts. How big does the difference have to be before you stop calling it chance?

The answer comes in two steps. First you make one number that says how far the whole table is from ‘independent’: χ². Then you look at how strange that number is when nothing is going on. Start with the deviation in each cell, fo−fef_\text{o} - f_\text{e}:

The deviation in each cell
cell fof_\text{o} fef_\text{e} fo−fef_\text{o} - f_\text{e}
bedroom, poorly 30 24 +6
bedroom, well 30 36 −6
elsewhere, poorly 10 16 −6
elsewhere, well 30 24 +6

Adding them up is no use: the deviations always add up to zero, because what one cell has too many, another has too few. So you square them, so that plus and minus no longer cancel each other out. And you divide each square by its own fef_\text{e}. Why? Six off when you expected 16 is more news than six off when you expected 36.

NoteThe χ2\chi^2 test statistic

χ2=∑(fo−fe)2fedf=(r−1)×(c−1) \chi^2 = \sum \dfrac{(f_\text{o} - f_\text{e})^2}{f_\text{e}} \qquad df = (r - 1) \times (c - 1)

  • ∑\sum: add up over all cells
  • dfdf: the degrees of freedom, with rr the number of rows and cc the number of columns (the total row and total column don’t count)

For the phone and sleep:

χ2=(30−24)224+(30−36)236+(10−16)216+(30−24)224=1.50+1.00+2.25+1.50=6.25 \begin{aligned} \chi^2 &= \dfrac{(30 - 24)^2}{24} + \dfrac{(30 - 36)^2}{36} + \dfrac{(10 - 16)^2}{16} + \dfrac{(30 - 24)^2}{24} \\[4pt] &= 1.50 + 1.00 + 2.25 + 1.50 \\[4pt] &= 6.25 \end{aligned}

Each term is that cell’s contribution to χ². The biggest comes from the smallest cell: 2.25, for the poor sleepers without their phone in the bedroom. There you expected 16 and saw only 10.

And the degrees of freedom: df=(2−1)×(2−1)=1df = (2 - 1) \times (2 - 1) = 1. That is the same as what you saw with the expected counts: in a two-by-two table, everything is fixed once you know one cell. With two rows and three columns, there are two; which two, you see in the answer to exercise 4.5. Look at the deviations too: in all four cells it is 6, only the sign changes.

That is no coincidence: in a two-by-two table it is always so. Put the deviations in the shape of the contingency table, and you see why:

The deviations fo−fef_\text{o} - f_\text{e} in the shape of the contingency table
sleeps poorly sleeps well total
in the bedroom +6 −6 0
elsewhere −6 +6 0
total 0 0 0

The whole table adds up to zero, and so does each row and each column on its own. That is because the expected counts have the same totals in the margins as the counted ones: in the row in the bedroom you counted 30+30=6030 + 30 = 60, and you expected 24+36=6024 + 36 = 60. So what one cell has too many, the other has too few. In a two-by-two table, once you know one deviation, you know all four. In a bigger table the rows and columns still add up to zero, but the deviations need not be the same size.

How strange is 6.25? Counting dots again

A χ² of 6.25. Is that a lot? The same question as in week 1, and the same thought experiment. Suppose H0H_0 is true: in the population of first-year students, phone location and sleep are not related. A hundred researchers each draw 100 first-year students, make their contingency table and work out χ². Each χ² becomes one dot, drawn as an open square:

A dot plot of open squares above an axis from 0 to 8. Just right of 0 is a tall stack of 49 squares; further right the stacks quickly get lower. At 6.25 there is an orange dashed line. To the right of it is one orange square.
Figure 2: A hundred values of χ², each from a sample of 100 first-year students, drawn from a population in which phone location and sleep are independent. One square is the χ² of one sample, stacked per half unit. Orange: the square beyond your 6.25.

How to read it: the height of a stack is the number of samples with a χ² in the half unit it stands on. Between 0 and 0.5 there are 49 stacked up, and to the right of your 6.25 there is one: in a world without association, a χ² close to 0 is very ordinary, and a χ² as big as yours is rare.

Three things stand out.

  • Everything lies to the right of 0. A χ² can’t be negative: it is a sum of squares, divided by positive numbers.
  • Most dots lie close to 0: 65 of the 100 are smaller than 1. Those are the two stacks to the left of 1, with 49 dots between 0 and 0.5 and 16 between 0.5 and 1. In a world without association, every table sits close to its expected counts, but rarely exactly on them.
  • To the right runs a long, thin tail. Now and then chance draws a table that is quite skewed.

Your 6.25 lies far out in that tail. Count the dots that are at least as big: one of the 100. So in a world without association, a table like that turns up about once in a hundred.

Worked out exactly, without a hundred dots, that shape is called the χ² distribution. Its shape depends on the degrees of freedom:

Three curves side by side, from left to right: at df = 1 the curve starts high at 0 and drops fast; at df = 2 it drops more gradually; at df = 3 it first rises to a hump around 1 and then drops. In each panel the part to the right of a dashed line is orange: at 3.84, 5.99 and 7.81. The three panels have the same vertical scale; at df = 1 the curve shoots up past the top edge at 0.
Figure 3: The χ² distribution with 1, 2 and 3 degrees of freedom. Orange: the right tail beyond the critical value at α = .05 (3.84, 5.99 and 7.81). In all three, the whole tail beyond the line is .05, including the part past the right edge.

How to read it: in all three panels the tail beyond the line is .05, but the line moves: at df=1df = 1 it is at 3.84, at df=3df = 3 only at 7.81. The more degrees of freedom, the bigger your χ² has to be before it falls in that tail.

The p-value is the area to the right of your χ². In R, first in full and then short:

# to the right of 6.25, in full: every argument by its name
pchisq(q = 6.25, df = 1, lower.tail = FALSE)
[1] 0.01241933
# short: the same call, the first argument without its name
pchisq(6.25, df = 1, lower.tail = FALSE)
[1] 0.01241933

Both give [1] 0.01241933. So p=.012p = .012, which is close to the .01 you counted.

q is your χ² and df the degrees of freedom. lower.tail = FALSE asks for the right tail: the area from 6.25 to the right. In the left panel of the figure above, your 6.25 lies to the right of the line at 3.84: the area from 6.25 onwards is a small piece of the orange area, and that piece is .012. You have to add that lower.tail = FALSE yourself. The default is lower.tail = TRUE: leave it out and R picks the area to the left of 6.25, and pchisq(6.25, df = 1) gives [1] 0.9875807: 1 minus your p.

TipWithout R: the critical value

At df=1df = 1 and α = .05, the critical value is 3.84. If your χ² is at or beyond 3.84, you reject H0H_0. Here: 6.25 ≥ 3.84, so reject.

Among the dots, five of the 100 were at or beyond 3.84: the four in the stack just past 4, and the orange one. The single dot just before 4 is a 3.75 and just misses. Five of the 100 is .05, as it should be.

Where 3.84 comes from, you’ll see below: it is 1.96 squared. Put 3.84 on your cheat sheet, next to 1.96. With more degrees of freedom the boundary lies further to the right (at df=2df = 2 it is 5.99). You don’t need to know that one by heart: in an exam, the p is given, or 3.84 is all you need.

NoteTwo ways: the χ² table and pchisq()

At the back, table F gives the boundaries for every df. With it you bracket your p between two columns. You do that to check yourself: the table and R should come out the same.

  • You choose the row by df. Here, row 1.
  • Find the two numbers your χ² lies between. In row 1, 5.41 is under column .02 and 6.63 under column .01. Your 6.25 lies between them. Careful, turn the order round here: a larger χ² goes with a smaller p. So .01 < p < .02.
  • Not times two. The column heading is the probability in the right tail, and for χ² that is already your whole p. You’ll see why below, in One tail, and yet it picks no side.

R gave p = .012: neatly in between, and both ways land below .05. You already know column .05 of row 1: 3.84.

One tail, and yet it picks no side

Week 1 already said that some tests pick no side, and that a one-sided version doesn’t even exist for them. This is one of those tests.

Look at the formula. Every deviation gets squared: 6 too many and 6 too few both give 36. The minus sign is gone. So χ² doesn’t know which way the association goes. Whether the people with their phone in the bedroom sleep poorly more often or less often: χ² gets big either way. It only measures how far the table is from ‘independent’.

Three things follow from that.

  • For χ², extreme only means big. A χ² of 0 is not extreme in the other direction; it means the counts are exactly the expected ones. That’s why you look at one tail: the right one.
  • You don’t multiply the p by two. Both directions of the association are already in that one right tail, because squaring has lumped them together. Times two would count them twice.
  • A one-sided test is impossible. For that you would have to say which direction you expect, and that direction has vanished in the square.

One tail, and still a test that reacts to an association in either direction: in that sense χ² is two-sided. In short: the tail says where you look, the side says whether you chose a direction beforehand. χ² is one-tailed, but two-sided.

Why 3.84: the fold

With a two-by-two table you can watch it happen. There, χ² is exactly the square of a z: the difference in the proportion of poor sleepers between the two groups, expressed in standard errors. Here 6.25=2.5\sqrt{6.25} = 2.5.

A z like that follows a smooth, symmetric bell, with a left half and a right half. A two-sided test at α = .05 means, there: .025 beyond −1.96 and .025 beyond 1.96. Square z, and the left half folds onto the right: −1.96 and 1.96 both become 1.962=3.841.96^2 = 3.84.

Two panels on the same scale, titled "z: two tails" and "χ² = z²: one tail". On the left a symmetric bell shape from −4 to 4 with two dashed lines at −1.96 and 1.96; the thin tails outside them are orange, each labelled .025. On the right a curve from 0 to 8 that shoots up past the top edge of the panel at 0 and drops steeply, with one dashed line at 3.84; the tail to the right of it is orange, labelled .05. That tail is lower and longer than either of the two tails in the left panel.
Figure 4: On the left, the bell of z, with .025 beyond −1.96 and .025 beyond 1.96. On the right, χ² with one degree of freedom: z squared. There the two tails of z lie together beyond 3.84: together .05, in one tail. Squaring does stretch that tail: lower and longer, but still .05.

How to read it: on the left there are two orange tails, each .025; on the right there is one, .05: in χ², the two tails of z, left and right, lie together in one tail.

That is why the critical value is 3.84, and why the ‘times two’ is already inside the right tail: the tail of z beyond 2.5 is .006, and twice that is .012, exactly the p of your χ².

Maybe you know χ² as a whale. It only gets its hump with more degrees of freedom. With one degree of freedom it is almost nothing but tail. Look again at Figure 3: at three degrees of freedom the hump is already there.

A small sketch shows a whale lying on a horizontal axis, with 0 below it on the left and χ² in the middle. Its back is the χ² distribution with three degrees of freedom: just after 0 it rises steeply to a hump, and then it runs out to the right in a long, thin tail, until just above the axis. There is an eye at the front, and a spout of water rises above its head.

Drawn as a whale: its back is the χ² distribution with three degrees of freedom from Figure 3.

The six steps

The same six steps as in week 1.

  1. Hypotheses.

    H0H_0: phone location and sleep are independent
    HaH_\text{a}: phone location and sleep are related

    Both about the population of first-year students. α = .05. In practice material from earlier years, this null hypothesis is sometimes written short, as H0H_0: fo=fef_\text{o} = f_\text{e}; it is still about the population, not about the counts in your sample.

  2. Sampling distribution. The χ² distribution with df=1df = 1.

  3. Test statistic. χ2=6.25\chi^2 = 6.25.

  4. p-value. p=.012p = .012, from the right tail. And .012 ≤ .05. Without R you see the same: 6.25 ≥ 3.84, and in table F you bracket your p between two columns: .01 < p < .02.

  5. Statistical conclusion. Reject the null hypothesis that phone location and sleep are independent.

  6. Conclusion in context. Among first-year students, phone location is related to how they sleep: in this sample, .50 of the people with their phone in the bedroom slept poorly, against .25 of the rest.

In a report, you put the test in one sentence, with the degrees of freedom and the number of people between the brackets:

This is how you report it

Phone location was associated with sleep, χ²(1, N = 100) = 6.25, p = .012.

You read which way the association goes in step 6, from the table, not from χ²: χ² picks no side. Look at the conditional probabilities, or at which cells are above their expected count.

For the phone: in the cell bedroom, poorly, you counted 30 where you expected 24, so +6. That’s where your story is: people with their phone in the bedroom sleep poorly more often than you would expect if the location didn’t matter.

The probabilities tell the same story: in that group the proportion of poor sleepers is .50, more than the .40 of everyone together. That .40 was in your expectation too: .40×60=24.40 \times 60 = 24. In a two-by-two table you don’t need to read the other three cells separately: they say the same from the other side. In elsewhere, poorly, for example, it says −6: fewer people there sleep poorly than expected.

You worked it out by hand. R does the same calculation alongside you, so that you can see it’s right. Type in the table row by row.

# the contingency table of the example, row by row
phone <- matrix(c(30, 30, 10, 30), nrow = 2, byrow = TRUE)

# the test without correction: the same calculation as by hand
out <- chisq.test(x = phone, correct = FALSE)
out

    Pearson's Chi-squared test

data:  phone
X-squared = 6.25, df = 1, p-value = 0.01242
# the expected counts
out$expected
     [,1] [,2]
[1,]   24   36
[2,]   16   24
# the p-value directly: only the right tail, not times two
pchisq(6.25, df = 1, lower.tail = FALSE)
[1] 0.01241933

Same χ², same expected counts, same p. x is your table. Watch correct = FALSE: the default is correct = TRUE, and if you leave it out, R picks that, and with a two-by-two table it gives a different number. The reason is below.

In the exam a graphing calculator is allowed, but a simple one is enough: everything above works on any calculator. If you have a TI-84, it does the whole test in one go. That is fine in the exam too; here it is a check on your work by hand.

  1. Open matrix [A]. 2nd, then x⁻¹ (MATRIX is printed above it). With ▶ ▶ to EDIT, then ENTER.
  2. The size. 2 ENTER 2 ENTER: first the rows, then the columns.
  3. The counts, row by row, each followed by ENTER: they are the four cells 30, 30, 10 and 30, not the totals.
  4. Back. 2nd, then MODE (QUIT is printed above it).
  5. Choose the test. STAT, with ▶ ▶ to TESTS, with ▼ to C:χ²-Test (not D:χ²GOF-Test), then ENTER.
  6. Calculate. Next to Observed it should say [A], and next to Expected [B] (that is where the calculator will put the expected counts itself). If it says something else, move the cursor there and choose the right one with 2nd x⁻¹, then ENTER. With ▼ to Calculate, then ENTER.
  7. Read it off. One below the other: χ²=6.25, then p=.0124…, then df=1: the same χ² and df as by hand, and the p from the six steps, with more decimals. A TI-84 Plus CE puts a zero in front (p=0.0124…). Write it down to three decimals and without the zero: p=.012p = .012.

Then open [B] the way you opened [A]. Your expected counts are there: 24, 36, 16 and 24.

With or without correction

Leave out correct = FALSE, and R picks the default, correct = TRUE: with a two-by-two table you get a different answer. Here correct = TRUE is written out, so you can see what R does then:

# correct = TRUE is the default: for two by two, Yates' correction
phone <- matrix(c(30, 30, 10, 30), nrow = 2, byrow = TRUE)
chisq.test(phone, correct = TRUE)

    Pearson's Chi-squared test with Yates' continuity correction

data:  phone
X-squared = 5.2517, df = 1, p-value = 0.02192

χ² is now 5.25 instead of 6.25, and p is .022 instead of .012. The heading line of the output says why: with Yates’ continuity correction.

What is that? Counts jump: you count 30 or 31 poor sleepers, never 30.4. The χ² distribution you take the p from is smooth. With a two-by-two table, especially with few people, that smooth distribution doesn’t quite fit, and the p comes out a little too small. So Yates’ continuity correction first moves each deviation half a unit closer to zero, before squaring: here (6−0.5)2=30.25(6 - 0.5)^2 = 30.25 instead of 62=366^2 = 36. That makes χ² smaller and p bigger: the test becomes more careful.

WarningWhat you do
  • By hand: without correction. That is the formula of this week. If a question asks for χ² for a table, that is the number it means.
  • R as a check on your handwork: chisq.test(..., correct = FALSE). Then you get exactly your own number back.
  • If you’re shown R output: take the p that is there, and look in the heading line to see which test it is. If it says with Yates’ continuity correction, that p is the one with the correction.
  • If the two lead to different decisions, you are on a borderline case (exercise 4.6). Follow what the question gives you. Given a table: calculate without correction. Given R output: use the p from that output. If you write a report yourself, say which version you used.

The correction only exists for a two-by-two table. With a bigger table, R calculates without correction.

Yates’ correction is a patch: the smooth χ² distribution doesn’t exactly fit counts that jump. There is also a test that doesn’t approximate at all, but works out every table with the same marginal totals exactly: Fisher’s exact test. In R it is called fisher.test(), and you give it the same table.

For the phone and sleep it gives p=.014p = .014, close to the .012 without and the .022 with correction. For the earplugs of exercise 4.6 it gives .057: there it sides with Yates. So a borderline case really is a borderline case.

You won’t calculate it this week; it’s good to know the name for when you meet it in a book or in R output.

What χ² doesn’t tell you

  • Which way. χ² has no direction. You read the direction from the table.
  • How strong. χ² grows with the number of people. Double the phone table (60, 60, 20 and 60): the probabilities stay exactly the same, but χ² becomes 12.50, twice as much. So a big sample makes even a small association significant. How strong an association is, you measure with an effect size; that comes in week 5 (Effect sizes and power).
  • What the cause is. That phone location and sleep are related doesn’t mean the phone ruins your sleep. Maybe it is the other way round, and poor sleepers reach for their phone more often because they’re lying awake anyway. The test only sees association.

In R: a contingency table and the test

Once again you use the practice dataset sleepstudy from week 1: 30 first-year students who sleep poorly, half of them with a sleep training, the other half without. With it you do four things in R: make a contingency table, draw it, do the χ² test, and ask for the expected counts.

The question: do people with a training improve more often? Improving is a category you make yourself here. Suppose the researchers agreed beforehand: anyone whose worry score afterwards is at least 3 points lower than before has improved.

## Load the data ----
load("sleepstudy.RData")
## A new column: who improved? ----
# ifelse(condition, what if TRUE, what if FALSE)
worry_drop <- sleepstudy$worry_before - sleepstudy$worry_after
sleepstudy$progress <- ifelse(worry_drop >= 3, "improved", "not improved")

## The contingency table ----
# first the variable you count, then the groups
counts <- table(sleepstudy$progress, sleepstudy$group)
counts
              
               control training
  improved           7        9
  not improved       8        6
# with the totals added
addmargins(counts)
              
               control training Sum
  improved           7        9  16
  not improved       8        6  14
  Sum               15       15  30

table() counts every combination. addmargins() adds the row and column totals: the margins, where the marginal probabilities come from.

In the training group, .60 improved (9 of the 15), in the control group .47.

The bar chart. Only barplot(counts, beside = TRUE) is needed; the rest is layout, and you may skip it.

## The bar chart ----
barplot(counts, beside = TRUE,         # bars side by side, not stacked
        legend.text = TRUE,            # a legend: which colour is which
        ylim = c(0, 15),               # the axis up to 15, so the legend fits
        xlab = "group", ylab = "count",   # names on the axes
        args.legend = list(title = "progress", x = "top", bty = "n"))
        # the legend at the top, with a title and no box
A bar chart with two pairs of bars, one pair for control and one for training. In each pair, a dark bar for improved and a light bar for not improved. For control the bar for not improved is a little higher than the bar for improved; for training the bar for improved is higher. So the dark bar, improved, is higher for training than for control.
Figure 5: Improvement per group in the sleep study. Dark: improved; light: not improved.

How to read it: the height of a bar is a number of people. The dark bar, improved, is taller for training (9) than for control (7). You may put those counts side by side because both groups have 15 people (9 + 6 and 7 + 8): in the training group a larger share improved.

Is that difference bigger than chance can make it? The test:

## The chi-square test ----
# the way R does it by default
# (for two by two: with Yates' correction)
chisq.test(sleepstudy$progress, sleepstudy$group,
           correct = TRUE)

    Pearson's Chi-squared test with Yates' continuity correction

data:  sleepstudy$progress and sleepstudy$group
X-squared = 0.13393, df = 1, p-value = 0.7144
# without correction, the way you calculate by hand
out <- chisq.test(sleepstudy$progress, sleepstudy$group,
                  correct = FALSE)
out

    Pearson's Chi-squared test

data:  sleepstudy$progress and sleepstudy$group
X-squared = 0.53571, df = 1, p-value = 0.4642
## The expected counts ----
out$expected
                   sleepstudy$group
sleepstudy$progress control training
       improved           8        8
       not improved       7        7

You can give chisq.test() two columns, as here, or a table you already have: chisq.test(counts, correct = FALSE) gives exactly the same. It is one test, called in two ways.

By hand you would get χ² = 0.54, and that is what R gives with correct = FALSE: p=.46p = .46. With correction it is p=.71p = .71. Both well above .05: you do not reject the null hypothesis that group and improvement are independent. With 30 people and an answer of only improved or not improved, you don’t see much. That doesn’t mean the training doesn’t work (week 1: not significant is not the same as equal).

TipFrom a score to a category: you throw something away

Someone whose worry score drops by 3 points and someone whose score drops by 11 are now both called improved. You’ve lost that difference. With the worry scores themselves, you can compare the two groups as in week 3, with two means. So making a category out of a score is a choice with a price; here you do it to practise in R.

Practice

NoteExercise 4.1 — Concepts
  1. What level of measurement do the variables have in a χ² test? And in a t test?
  2. When are two categorical variables independent?
  3. Give the formula for:
    1. the multiplication rule for independent variables;
    2. the multiplication rule that always holds;
    3. the expected count fef_\text{e} in a cell;
    4. the χ² test statistic;
    5. the degrees of freedom of χ².
  4. What does a χ² of 0 mean?
  5. What does a large χ² mean?
  6. Why can’t χ² be negative? And why does that make the χ² distribution skewed to the right?
  7. With χ² you look at one tail, and yet you call the test two-sided. Explain.
  1. In a χ² test: categorical (nominal or ordinal); you count how often each combination occurs. In a t test, the dependent variable is a score on a scale (interval or ratio), because you compare means.

  2. When one tells you nothing about the other. In a table: the conditional probabilities are equal in all groups, and so also equal to the marginal probability.

  3. The formulas:

    1. P(A and B)=P(A)×P(B)P(A \text{ and } B) = P(A) \times P(B)
    2. P(A and B)=P(A)×P(B∣A)P(A \text{ and } B) = P(A) \times P(B \mid A)
    3. fe=row total×column totalNf_\text{e} = \dfrac{\text{row total} \times \text{column total}}{N}
    4. χ2=∑(fo−fe)2fe\chi^2 = \sum \dfrac{(f_\text{o} - f_\text{e})^2}{f_\text{e}}
    5. df=(r−1)×(c−1)df = (r - 1) \times (c - 1), with rr rows and cc columns
  4. That the counts are exactly the expected ones: in the sample there is no association at all.

  5. That the counts are far from the expected ones. If χ² is big enough (p≤.05p \leq .05), you reject the null hypothesis that the variables are independent.

  6. χ² is a sum of squares, divided by positive numbers; nothing negative can come out of that. So the distribution starts at 0, most values lie close to it, and to the right runs a long tail. To the left it has nowhere to go.

  7. One tail, because only a big χ² is extreme: your p is the area to the right of your χ². Two-sided, because squaring removes the minus sign: χ² reacts to an association in either direction. A cell can have too many or too few, and because the totals are fixed, another cell then automatically has the opposite. That is also why you don’t multiply the p by two. χ² is one-tailed, but two-sided.

NoteExercise 4.2 — Only the marginal totals

For 100 first-year students you know whether they had breakfast that morning, and whether they fell asleep during the day. You only know the totals:

had breakfast fell asleep did not fall asleep total
yes … … 70
no … … 30
total 20 80 100
  1. Fill in the counts you expect if having breakfast and falling asleep are independent. The cells have to add up to the totals.
  2. Now make up counts with a clear association. These too have to add up to the totals. There is more than one right answer.
  1. Row total times column total, divided by 100:

    had breakfast fell asleep did not fall asleep total
    yes 14 56 70
    no 6 24 30
    total 20 80 100

    For example, top left: 70×20100=14\dfrac{70 \times 20}{100} = 14. The rest follows by subtraction. Now the same share falls asleep in both rows: 1470=630=.20\dfrac{14}{70} = \dfrac{6}{30} = .20.

  2. The extreme example: all 20 who fell asleep had skipped breakfast.

    had breakfast fell asleep did not fall asleep total
    yes 0 70 70
    no 20 10 30
    total 20 80 100

    Any table in which the share who fell asleep clearly differs between the two rows is right.

NoteExercise 4.3 — The test by hand

Researchers ask 240 first-year students whether they have an evening job, and whether on weekdays they usually sleep less than seven hours (short) or not (long).

evening job short long total
yes 50 40 90
no 60 90 150
total 110 130 240
  1. What do the researchers want to know?
  2. Write down H0H_0 and HaH_\text{a}.
  3. Work out the expected counts for all cells.
  4. Work out each cell’s contribution to χ², and then χ² itself.
  5. Work out the p-value with pchisq(). Watch the degrees of freedom. (No R to hand? You can still decide: compare with 3.84.)
  6. What is your statistical conclusion at α = .05?
  7. What is your conclusion in context?
  1. The expected counts are 41.25, 48.75, 68.75 and 81.25.
  2. χ² = 5.48.
  3. df = 1; p=.019p = .019.
  4. Reject.
  5. Having an evening job is related to how long you sleep: with an evening job, you more often sleep less than seven hours.
  1. Whether having an evening job is related to how long first-year students sleep. In other words: whether the two variables are dependent.

  2. The hypotheses:

    H0H_0: having an evening job and sleep length are independent
    HaH_\text{a}: having an evening job and sleep length are related

  3. Row total times column total, divided by 240:

    • yes, short: 90×110240=41.25\dfrac{90 \times 110}{240} = 41.25
    • yes, long: 90×130240=48.75\dfrac{90 \times 130}{240} = 48.75
    • no, short: 150×110240=68.75\dfrac{150 \times 110}{240} = 68.75
    • no, long: 150×130240=81.25\dfrac{150 \times 130}{240} = 81.25

    Check: the rows add up to 90 and 150, the columns to 110 and 130.

  4. Per cell:

    cell fof_\text{o} fef_\text{e} fo−fef_\text{o} - f_\text{e} (fo−fe)2fe\dfrac{(f_\text{o} - f_\text{e})^2}{f_\text{e}}
    yes, short 50 41.25 +8.75 1.856
    yes, long 40 48.75 −8.75 1.571
    no, short 60 68.75 −8.75 1.114
    no, long 90 81.25 +8.75 0.942
    χ² 5.48

    Keep calculating with the unrounded numbers in your calculator, and only round the final answer.

  5. df=(2−1)×(2−1)=1df = (2 - 1) \times (2 - 1) = 1. Only the right tail, not times two:

    pchisq(5.483, df = 1, lower.tail = FALSE)
    [1] 0.01920228
    # and the whole test as a check
    evening_job <- matrix(c(50, 40, 60, 90), nrow = 2, byrow = TRUE)
    chisq.test(evening_job, correct = FALSE)
    
     Pearson's Chi-squared test
    
    data:  evening_job
    X-squared = 5.4825, df = 1, p-value = 0.01921

    So p=.019p = .019.

  6. .019 ≤ .05: reject the null hypothesis that having an evening job and sleep length are independent. Without R you would have seen it too: 5.48 ≥ 3.84.

  7. Among first-year students, having an evening job is related to how long they sleep. In this sample, .56 of the people with an evening job slept less than seven hours, against .40 of the people without one. Whether the job is the cause, the test doesn’t say: maybe people who go to bed late anyway are more likely to take an evening job.

NoteExercise 4.4 — In R

Use the dataset sleepstudy. Did the random assignment work out? With a good random assignment, worrying before the training is not related to the group someone ends up in.

  1. Make a column worried that is "a lot" if someone scored more than 55 on the worry questionnaire before the training, and "not a lot" otherwise.
  2. Make a contingency table of worried against group, with the totals added.
  3. Do the χ² test without correction. What is the p-value, and what do you decide?
  4. Ask for the expected counts.
  5. Does your answer to c mean that the groups worried equally at the start?
## a. the new column ----
sleepstudy$worried <- ifelse(sleepstudy$worry_before > 55, "a lot", "not a lot")

## b. the contingency table ----
counts_worried <- table(sleepstudy$worried, sleepstudy$group)
addmargins(counts_worried)
           
            control training Sum
  a lot           7        6  13
  not a lot       8        9  17
  Sum            15       15  30
## c. the test, without correction ----
out_worried <- chisq.test(sleepstudy$worried, sleepstudy$group, correct = FALSE)
out_worried

    Pearson's Chi-squared test

data:  sleepstudy$worried and sleepstudy$group
X-squared = 0.13575, df = 1, p-value = 0.7125
## d. the expected counts ----
out_worried$expected
                  sleepstudy$group
sleepstudy$worried control training
         a lot         6.5      6.5
         not a lot     8.5      8.5
  1. χ² = 0.14, p=.71p = .71. You do not reject the null hypothesis that worrying a lot at the start and the group are independent.

  2. See the output: in each group you expect 6.5 people who worry a lot, because the groups are the same size.

  3. No. Not significant is not the same as equal. You just haven’t found any sign that the assignment came out lopsided; that is what you hope, but it is no proof that the groups are equal.

NoteExercise 4.5 — Probabilities from a bigger table

A group of 400 students fill in how tired they usually feel during the day.

hardly somewhat very total
first year 85 95 70 250
later years 75 45 30 150
total 160 140 100 400

Draw one of these students at random. What is the probability that this student …

  1. is in their first year and feels very tired?
  2. feels hardly tired?
  3. feels very tired, given that they are in a later year?
  4. Are year of study and tiredness independent for these 400 students? Look only at the probabilities; don’t do a test.
  5. For this table, R gives X-squared = 10.114, df = 2 and p-value = 0.006364. Why is df 2 here, and what do you decide about the population?
  6. Suppose year of study and tiredness are independent. How many first-year students who feel hardly tired would you expect then?

a. A joint probability: one cell, divided by everyone.

hardlysomewhatverytotal
first year859570250
later years754530150
total160140100400
P(first year and very tired)=70400=.175
  • the barrel is everyone (double border): the whole table is in it
  • 70 above the line: the cell first year, very
  • 400 below the line: everyone, the whole barrel

b. A marginal probability: the column total, divided by everyone.

hardlysomewhatverytotal
first year859570250
later years754530150
total160140100400
P(hardly tired)=160400=.40
  • the barrel is everyone (double border): the whole table is in it
  • 160 above the line: everyone in the column hardly
  • 400 below the line: everyone, the whole barrel

c. A conditional probability: the barrel is now only the 150 students in a later year.

hardlysomewhatverytotal
first year859570250
later years754530150
total160140100400
P(very tired∣later years)=30150=.20
  • the barrel (solid border, also under the words in the fraction): only the row later years is still in it
  • 30 above the line: the cell later years, very
  • 150 below the line: everyone in the row later years, the whole barrel
  • light numbers, outside the border of the barrel: not in it

d. No. The barrel here is the row: all first-year students, or all students in a later year. Then go along column by column and compare the two rows:

hardly somewhat very
first year .34 .38 .28
later years .50 .30 .20
everyone .40 .35 .25

They are not equal: of the first-year students, .28 feel very tired, of the students in a later year .20. So in this group, year of study and tiredness are dependent.

e. df=(2−1)×(3−1)=2df = (2 - 1) \times (3 - 1) = 2: two rows and three columns. p=.006≤.05p = .006 \leq .05: you reject the null hypothesis that year of study and tiredness are independent. In the population, too, they are related. (The critical value at df=2df = 2 is 5.99, and 10.11 lies beyond it.)

Why two? Suppose you only know the totals in the margins of this table. Then you can fill in two cells freely, and you complete the rest straight away: not guessing, but working it out. Here the free cells are black: those are the ones you choose.

hardlysomewhatverytotal
first yearfree85free95follows70250
later yearsfollows75follows45follows30150
total160140100400
  • 85 95 free: you may choose these two cells yourself; the totals around them are fixed
  • follows: work it out with a row or column total; a number without a box in such a sum followed already
  • first year, very: 250 − 85 − 95 = 70
  • later years, hardly: 160 − 85 = 75
  • later years, somewhat: 140 − 95 = 45
  • later years, very: 100 − 70 = 30
  • check, the row later years: 75 + 45 + 30 = 150
  • you don't need the grand total N, 400, here

So two cells are free, and the other four are fixed. In any table you can choose the block at the top left: all rows except the last, and all columns except the last. That is (2−1)×(3−1)(2 - 1) \times (3 - 1). Two cells in one column won’t do: at later years, hardly you can see that the 75 is fixed as soon as the 85 is there.

f. Row total times column total, divided by NN. There are no hits in the fraction, only totals:

hardlysomewhatverytotal
first yearcounted859570250
later years754530150
total160140100400
fe=row total×column totalN=250×160400=40000400=100
  • 250 the row total: everyone in the row first year
  • 160 the column total: everyone in the column hardly
  • 400 the grand total N: everyone
  • the cell you work out fe for; you counted 85 there, and you do not need that number for fe
  • light numbers without a box: not in the sum

You counted 85, fewer than the 100 you would expect if year of study made no difference.

NoteExercise 4.6 — With or without correction

For a week, 120 first-year students sleep with or without earplugs. Afterwards they say whether they woke up during the night.

woke up did not wake up total
earplugs 10 50 60
no earplugs 20 40 60
total 30 90 120
  1. Work out χ² by hand. Do you reject H0H_0 at α = .05?

A fellow student does the same test in R, with chisq.test(), and gets this:

earplugs <- matrix(c(10, 50, 20, 40), nrow = 2, byrow = TRUE)
# R's default: correct = TRUE, even if you leave it out
chisq.test(earplugs, correct = TRUE)

    Pearson's Chi-squared test with Yates' continuity correction

data:  earplugs
X-squared = 3.6, df = 1, p-value = 0.05778
  1. Why does a different number come out there? And what do you write down if you use this output?
  2. Two ways. Look up your χ² from a and your fellow student’s in table F, row df = 1. Which side of 3.84 do they lie on, between which two columns, and what does that mean for their p? Does that match R? For your χ², pchisq(4.44, df = 1, lower.tail = FALSE) gives the p; your fellow student’s is in the output above.
  1. The expected counts are 15, 45, 15 and 45, and each deviation is 5:

    χ2=5215+5245+5215+5245=4.44 \chi^2 = \dfrac{5^2}{15} + \dfrac{5^2}{45} + \dfrac{5^2}{15} + \dfrac{5^2}{45} = 4.44

    With df=1df = 1: 4.44 ≥ 3.84. Reject. (R gives p=.035p = .035; for what table F says about it, see c.)

  2. With a two-by-two table, R applies Yates’ correction by default: correct = TRUE is the default, even if you leave it out, and the heading line says so too. First each deviation moves half a unit closer to zero: (5−0.5)2(5 - 0.5)^2 instead of 525^2. Then χ² = 3.60, and that lies below 3.84: p=.058p = .058, do not reject.

    This is a borderline case: the two routes give a different decision. What you do depends on what you’re given:

    • if you only get the table, you calculate without correction: reject;
    • if you get this output, you take the p that is there: do not reject;
    • if you write a report yourself, you say that it is the version with the correction, and that with it, the result is only just not significant.
    This is how you report it

    With Yates’ correction, wearing earplugs was not significantly associated with waking up at night, χ²(1, N = 120) = 3.60, p = .058.

    What is never allowed: picking the version that suits you best, after you saw both. That is the same cheating as choosing the direction after seeing the data (week 1).

  3. In row 1 of table F:

    The borderline case of exercise 4.6 in table F
    lies between so R gives
    your χ² = 4.44 (without correction) 3.84 (column .05) and 5.02 (column .025) .025 < p < .05 p = .035
    your fellow student’s χ² = 3.60 (with correction) 2.71 (column .10) and 3.84 (column .05) .05 < p < .10 p = .058

    Both agree with R. And in the table you see the borderline case at once: moving each deviation half a unit closer to zero, as the correction does, shifts χ² one column to the left, across the boundary at 3.84. Not times two: for χ², the column heading is already your whole p.

Exam block

This is how you might meet it in the exam: as a multiple-choice question with four options. The exam has 30 of them. Below there are also a few questions you fill in yourself or answer with yes or no; the exam does not have those, they are extra practice. All you need is your calculator and your cheat sheet: where you need a p-value, it is given in the question. Or, for a two-by-two table, you decide with the boundary 3.84 from your cheat sheet. The exam does not ask you to look anything up in table F; you did that in exercise 4.6, to check yourself.

Questions 1 and 2 are about this table of 80 first-year students:

Alarms and being on time, for 80 first-year students
on time late total
two alarms 40 10 50
one alarm 18 12 30
total 58 22 80
NoteQuestion 1 — multiple choice

What is the probability of being on time, given that you set two alarms? And are the number of alarms and being on time dependent, for these 80 first-year students?

  1. .50; dependent
  2. .80; dependent
  3. .50; independent
  4. .80; independent

B. The barrel is the 50 people with two alarms: 4050=.80\dfrac{40}{50} = .80. With one alarm it is 1830=.60\dfrac{18}{30} = .60. Not equal, so dependent, in this group. .50 is the trap: that is 4080\dfrac{40}{80}, the joint probability of two alarms and on time.

NoteQuestion 2 — multiple choice

How many people with two alarms do you expect in the column late, if the number of alarms and being on time are independent?

  1. 10
  2. 8.25
  3. 13.75
  4. .275

C. 50×2280=13.75\dfrac{50 \times 22}{80} = 13.75. A is the number you counted, not the one you expected. B is the expected count in the row below. D is the probability of being late, not yet a count: you still have to multiply it by 50.

Questions 3 and 4 are about this table of 100 first-year students:

Sport in the evening and falling asleep, for 100 first-year students
falls asleep within 20 minutes does not fall asleep within 20 minutes total
sport in the evening 25 25 50
no sport 30 20 50
total 55 45 100
NoteQuestion 3 — multiple choice

You want to test whether sport in the evening and falling asleep quickly are related. What is χ² for this table?

  1. χ² = 0.31
  2. χ² = 1.01
  3. χ² = 3.84
  4. χ² = 25.00

B. The expected counts are 27.5 and 22.5 in both rows, and the deviation is 2.5 in every cell:

χ2=2.5227.5+2.5222.5+2.5227.5+2.5222.5=1.01 \chi^2 = \dfrac{2.5^2}{27.5} + \dfrac{2.5^2}{22.5} + \dfrac{2.5^2}{27.5} + \dfrac{2.5^2}{22.5} = 1.01

The other three are each a well-known mistake. A is the p-value that goes with this χ² (in table F, 1.01 lies even further left than the first column of row 1, so p > .25). C is not a χ² of this table but the critical value at df=1df = 1: in table F, row 1, column .05. You also come across it with three decimals, as 3.841. D is what you get if you add up the squares and forget to divide by fef_\text{e}.

NoteQuestion 4 — yes or no

At that χ², do you reject the null hypothesis (α = .05)?

No. 1.01 lies below the critical value 3.84 (p=.31p = .31). You do not reject the null hypothesis that sport in the evening and falling asleep quickly are independent.

NoteQuestion 5 — fill in

A contingency table has 3 rows and 4 columns (not counting the totals). How many degrees of freedom does the χ² test have?

6. (3−1)×(4−1)=2×3=6(3 - 1) \times (4 - 1) = 2 \times 3 = 6.

NoteQuestion 6 — multiple choice

Why don’t you multiply the p-value of a χ² test by two?

  1. Because the χ² test is one-sided.
  2. Because both directions of the association are already in the right tail.
  3. Because the χ² distribution is symmetric.
  4. Because with categorical variables you have no null hypothesis.

B. Squaring removes the minus sign, so too many and too few both end up on the right. A is the trap: you look at one tail, but the test is not one-sided; it reacts to an association in either direction. C is wrong: the χ² distribution is skewed to the right. D is wrong: H0H_0 says that the variables are independent.

NoteQuestion 7 — multiple choice

A researcher wants to know whether choosing tea or coffee is related to year of study. Which null hypothesis goes with a χ² test?

  1. Choice and year of study are independent.
  2. Choice and year of study are dependent.
  3. First-year students choose coffee more often than students in later years.
  4. The mean year of study is the same for coffee drinkers as for tea drinkers.

A. H0H_0 says that nothing is going on: no association. B is HaH_\text{a}. C picks a direction, and χ² has none. D is about means; year of study is a category here.

NoteQuestion 8 — multiple choice

Someone does the test of exercise 4.3 in R, with chisq.test() and no further settings. At the top of the output it says Pearson’s Chi-squared test with Yates’ continuity correction, and below that X-squared = 4.8738, df = 1 and p-value = 0.02727. Which statement is right?

  1. R made a mistake, because by hand χ² = 5.48 came out.
  2. R used a correction; without that correction χ² would be a little bigger.
  3. Because of the correction, you may no longer reject H0H_0.
  4. You still have to multiply R’s p by two.

B. With the correction, R first moves each deviation half a unit closer to zero; that makes χ² smaller. With correct = FALSE you get the 5.48 of your handwork back. C is wrong: even with the correction, p = .027 ≤ .05. D is wrong: χ² has one tail, and that one tail already holds both directions of the association.

NoteQuestion 9 — yes or no

“We found χ²(1, N = 400) = 18.40, p < .001. So year of study is strongly related to sleep length.” Is the second sentence right?

No. Significant says that there is an association, not how strong it is. With a great many people, even a small association becomes significant. How strong it is, an effect size tells you (week 5).

NoteQuestion 10 — multiple choice

A researcher asks 300 first-year students whether they drink coffee in the evening, and whether they usually fall asleep within half an hour. Of them, 120 drink coffee in the evening, and 180 do not. Of the coffee drinkers, 78 usually fall asleep within half an hour. Of the first-year students without coffee, 117 usually fall asleep within half an hour.

Is falling asleep within half an hour independent of coffee in the evening, in this group? And what is the probability that a first-year student drawn at random from this group drinks coffee in the evening and falls asleep within half an hour?

  1. dependent; .26
  2. dependent; .65
  3. independent; .26
  4. independent; .65

C. There is no table here, so first you put the counts into a contingency table yourself. Quick means: asleep within half an hour. What the question doesn’t give you, you find by subtracting and adding:

Coffee in the evening and falling asleep, for 300 first-year students, built from the question
quick not quick total
coffee 78 42 120
no coffee 117 63 180
total 195 105 300

Independent? Don’t compare the counts; compare the conditional probabilities, and put the marginal probability on a third line:

P(quick∣coffee)=78120=.65P(quick∣no coffee)=117180=.65P(quick)=195300=.65 \begin{aligned} P(\text{quick} \mid \text{coffee}) &= \dfrac{78}{120} = .65 \\ P(\text{quick} \mid \text{no coffee}) &= \dfrac{117}{180} = .65 \\ P(\text{quick}) &= \dfrac{195}{300} = .65 \end{aligned}

Exactly .65, all three times: in each group, the same share falls asleep quickly as in the whole table. So independent, in this group. With real data you almost never see that, and that is why you might not trust it. Then check it by multiplying: 120×.65=78120 \times .65 = 78 and 180×.65=117180 \times .65 = 117.

More people without coffee fall asleep quickly (117 against 78), but only because that group is bigger (180 against 120). If you compare the counts, or go by what everyone knows about coffee, you choose dependent. But the question is about this group, and there the numbers decide.

The probability. In Figure 6 only the barrel changes, not the hits.

Two lucky-dip barrels side by side, the same width, each drawn as a plain outline, a little wider at the top; the left one is tall, the right one only .40 times as tall (120 of the 300), and it sits at the height of the top row of the left one, as if that row had been slid out sideways. The left barrel is divided into four areas, each as large as its count, laid out like the contingency table: at the top the row of the coffee drinkers, with on the left the hits: an orange area '78, coffee and quick', and on the right a light blue area '42, coffee, not quick'; below that, in a taller row because that group is larger, two grey areas, on the left '117, no coffee, quick' and on the right '63, no coffee, not quick'. The boundary between quick and not quick lies in the same place in both rows, and a thin dark line, in the colour of the outline, runs along that boundary through the whole barrel. The right barrel is exactly that top row on its own: the same orange area and the same light blue area, as large as on the left, with the same words in them and the same thin line on the boundary between them. Above the left barrel it says 'barrel: everyone (300)', below it 'P(coffee and quick) = 78/300 = .26'; above the right one 'barrel: only the coffee drinkers (120)', below it 'P(quick | coffee) = 78/120 = .65', in words: the probability of quick, given coffee. So each fraction is the orange part of the barrel it stands under.
Figure 6: Orange is coffee and quick: the hits. Each area is as large as its count, and the fraction under a barrel is the orange part of that barrel. The right barrel is only the top row of the left one: the coffee drinkers. In the left barrel, the boundary between quick and not quick lies in the same place in both rows: that is the independence you just found, in a picture.

How to read it: on the left, the orange area is 78 of the 300 first-year students: .26 of the barrel. On the right, the same area is 78 of the 120: .65 of the barrel. The same hits, but a smaller barrel, and so a bigger probability.

The question has no given that: the first-year students without coffee are simply still in the barrel. So the barrel is everyone, all 300, and the hits are the 78 coffee drinkers who fall asleep quickly:

P(coffee and quick)=78300=.26 P(\text{coffee and quick}) = \dfrac{78}{300} = .26

The trap is .65, the number you just saw three times. That is the answer to a different question: what is the probability that a coffee drinker falls asleep quickly? Can you hear the difference? There the barrel is only the 120 coffee drinkers.

Counting and dividing is always allowed. The product rule is a second route, and it is allowed only because coffee and falling asleep quickly are independent in this group:

P(coffee)=120300=.40P(coffee)×P(quick)=.40×.65=.26 \begin{aligned} P(\text{coffee}) &= \dfrac{120}{300} = .40 \\ P(\text{coffee}) \times P(\text{quick}) &= .40 \times .65 = .26 \end{aligned}

The same number. With the phone in the bedroom, the product rule gave .24 and the table .30: there the two were related, so the rule was not allowed.

Back to top