# Load libraries
library(readxl)
library(tidyverse)
library(confintr) # for effect size calculation
# Load data
genitive <- read_xlsx("Grafmiller_genitive_alternation.xlsx")3.5 Chi-squared test
The chi-squared (\(\chi^2\)) test helps determine if there is a statistically significant association between two categorical variables. It compares the observed frequencies of categories with those expected under the null hypothesis. The \(\chi^2\) (chi-squared) score quantifies the differences between observed and expected frequencies across all cells of a contingency table. The greater the difference between observed and expected, the higher the \(\chi^2\) score and the lower the \(p\)-value, given the degrees of freedom. It is recommended to compute effect size measures and inspect the residuals to assess the nature of the association.
Recommended reading
For linguists:
Gries (2021): Chapter 4.1.2.1
General:
Baguley (2012): Chapter 4
Agresti and Kateri (2022): Chapter 5
Preparation
You can find the full R script associated with this unit here.
The Pearson \(\chi^2\)-test of independence
The first step of any significance test involves setting up the null and alternative hypotheses. In this unit, we will perform a sample analysis of the relationship between genitive Type and Possessor Animacy. Specifically, we will focus on the independence of these two discrete variables (i.e., the presence or absence of an association).
\(H_0:\) The variables
TypeandPossessor Animacyare independent.\(H_1:\) The variables
TypeandPossessor Animacyare not independent.
Next, we compute a test statistic that indicates how strongly our data deviate from the frequencies expected under \(H_0\). To this end, we will need two types of values:
the observed frequencies \(f_{ij}\) present in our dataset
the expected frequencies \(e_{ij}\), which we would expect to see if \(H_0\) were true,
where the observed frequencies are counts (\(f_{ij} \in \mathbb{N}\)), whereas the expected frequencies are usually not whole numbers (\(e_{ij} \geq 0\)). The indices \(i\) and \(j\) uniquely identify the cell counts in all column-row combinations of a contingency table. Reframing the hypotheses in terms of these two quantities, we have:
\(H_0:\) Any differences between the observed frequencies \(f_{ij}\) and the expected frequencies \(e_{ij}\) are merely due to chance (i.e., random sampling error).
\(H_1:\) The differences between \(f_{ij}\) and \(e_{ij}\) (in at least one cell) are too large to be attributed to chance alone and reflect an association in the population.
Note that even if \(H_0\) is true, the observed frequencies will hardly ever match the expected ones exactly – the question is whether the deviations are larger than what we would expect from random sampling.
Observed frequencies
The table below represents a generic contingency table where \(Y\) and \(X\) are categorical variables and have the values \(Y = \{y_1, y_2, \dots, y_I \}\) and \(X = \{x_1, x_2, \dots, x_J\}\). In the table, each cell indicates the number of observations \(f_{ij}\) corresponding to the \(i\)-th row and \(j\)-th column.
| \(X\) | ||||||
|---|---|---|---|---|---|---|
| \(x_1\) | \(x_2\) | … | \(x_J\) | |||
| \(y_1\) | \(f_{11}\) | \(f_{12}\) | … | \(f_{1J}\) | ||
| \(y_2\) | \(f_{21}\) | \(f_{22}\) | … | \(f_{2J}\) | ||
| \(Y\) | … | … | … | … | … | |
| \(y_I\) | \(f_{I1}\) | \(f_{I2}\) | … | \(f_{IJ}\) |
In the genitive data, the observed frequencies correspond to how often each Type value (i.e., s and of) is attested for a given Possessor Animacy group (i.e., animate and inanimate). These can be computed in a very straightforward fashion by applying R’s table() function to the variables of interest.
observed_freqs <- table(genitive$Type, genitive$Possessor_Animacy2)
print(observed_freqs)
animate inanimate
of 592 2511
s 1451 544
Expected frequencies
The expected frequencies require a few additional steps. Usually, these steps are performed automatically when conducting the chi-squared test in R, so you don’t have to worry about calculating them by hand. We will do it anyway to drive home the rationale of the test.
| \(X\) | ||||||
|---|---|---|---|---|---|---|
| \(x_1\) | \(x_2\) | … | \(x_J\) | |||
| \(y_1\) | \(e_{11}\) | \(e_{12}\) | … | \(e_{1J}\) | ||
| \(y_2\) | \(e_{21}\) | \(e_{22}\) | … | \(e_{2J}\) | ||
| \(Y\) | … | … | … | … | … | |
| \(y_I\) | \(e_{I1}\) | \(e_{I2}\) | … | \(e_{IJ}\) |
The expected frequencies \(e_{ij}\) are given by the formula in Equation 1.
\[ e_{ij} = \frac{i\textrm{th row sum} \times j \textrm{th column sum}}{\textrm{sample size}} \tag{1}\]
In concrete terms, we go through each cell in the cross-table and multiply the corresponding row sum by the corresponding column sum, dividing the result by the total number of observations in the sample. For example, there are \(592\) occurrences of of genitives in the animate group. The row sum is \(592+ 2511 = 3103\) and the column sum is \(592 + 1451 = 2043\). Next, we take their product \(3103 \cdot 2043\) and divide it by the total number of observations, which is \(592 + 2511 + 1451 + 544 = 5098\). Thus, we obtain an expected frequency of \(\frac{3103 \times 2043}{5098} \approx 1243.51\) under the null hypothesis.
The expected frequencies for our combination of variables are shown below. In which cells can you see the greatest deviations between observed and expected frequencies?
Show the code
## Calculate row totals
row_totals <- rowSums(observed_freqs)
## Calculate column totals
col_totals <- colSums(observed_freqs)
## Total number of observations
total_obs <- sum(observed_freqs)
## Calculate expected frequencies
expected_freqs <- outer(row_totals, col_totals) / total_obs
print(expected_freqs) animate inanimate
of 1243.5129 1859.487
s 799.4871 1195.513
Conducting the test
The \(\chi^2\)-test now offers a convenient way of quantifying the differences between the two tables above. It measures how much the observed frequencies deviate from the expected frequencies in each cell of a contingency table and adds up these deviations (cf. Heumann, Schomaker, and Shalabh 2022: 249–251). The gist of this procedure is summarised in Equation 2.
\[ \chi^2 = \sum_{\text{all cells}} \frac{(\text{observed} - \text{expected})^2}{\text{expected}} \tag{2}\]
Let \(I\) denote the total number of rows and \(J\) the total number of columns, with degrees of freedom (\(df\)) equal to \((I-1) \cdot (J-1)\). We compute the squared deviations between \(f_{ij}\) and \(e_{ij}\) for every row-column combination, divide each by \(e_{ij}\) and sum them up:
\[ \chi^2 = \frac{(f_{11} - e_{11})^2}{e_{11}} + \frac{(f_{12} - e_{12})^2}{e_{12}} + \frac{(f_{21} - e_{21})^2}{e_{21}} + \frac{(f_{22} - e_{22})^2}{e_{22}} + \dots + \frac{(f_{IJ} - e_{IJ})^2}{e_{IJ}} \tag{3}\]
In crisp summation notation:
\[ \chi^2 = \sum_{i=1}^{I}\sum_{j=1}^{J}{\frac{(f_{ij} - e_{ij})^2}{e_{ij}}} \tag{4}\]
The piecewise calculation of \(\chi^2\) is summarised in the table below:
| \(X\) | ||||||
|---|---|---|---|---|---|---|
| \(x_1\) | \(x_2\) | … | \(x_J\) | |||
| \(y_1\) | \(\frac{(f_{11} - e_{11})^2}{e_{11}}\) | \(\frac{(f_{12} - e_{12})^2}{e_{12}}\) | … | \(\frac{(f_{1J} - e_{1J})^2}{e_{1J}}\) | ||
| \(y_2\) | \(\frac{(f_{21} - e_{21})^2}{e_{21}}\) | \(\frac{(f_{22} - e_{22})^2}{e_{22}}\) | … | \(\frac{(f_{2J} - e_{2J})^2}{e_{2J}}\) | ||
| \(Y\) | … | … | … | … | … | |
| \(y_I\) | \(\frac{(f_{I1} - e_{I1})^2}{e_{I1}}\) | \(\frac{(f_{I2} - e_{I2})^2}{e_{I2}}\) | … | \(\frac{(f_{IJ} - e_{IJ})^2}{e_{IJ}}\) |
The implementation in R is a simple one-liner. Keep in mind that we have to supply absolute frequencies to chisq.test() rather than percentages.
freqs_test <- chisq.test(observed_freqs)
print(freqs_test)
Pearson's Chi-squared test with Yates' continuity correction
data: observed_freqs
X-squared = 1453.4, df = 1, p-value < 2.2e-16
Note that for \(2 \times 2\) tables, chisq.test() applies Yates’ continuity correction by default, which slightly reduces the \(\chi^2\) value. If you calculate \(\chi^2\) by hand using Equation 4, you will therefore obtain a slightly higher value, which corresponds to chisq.test(observed_freqs, correct = FALSE).
Quite conveniently, the test object freqs_test stores the expected frequencies, which can be easily accessed via subsetting. Luckily, they are identical to what we calculated above!
freqs_test$expected
animate inanimate
of 1243.5129 1859.487
s 799.4871 1195.513
Assumptions of the chi-squared test
This \(\chi^2\)-test comes with certain statistical assumptions. Violations of these assumptions decrease the validity of the result and could, therefore, lead to wrong conclusions about relationships in the data. In this case, other tests should be consulted.
- All observations are independent of each other.
- At least 80% of the expected frequencies are \(\geq\) 5 (for \(2 \times 2\) tables: all of them).
- All expected frequencies are \(\geq\) 1.
Dependent observations (e.g., multiple measurements per participant) are a common problem of linguistic data and should always be controlled for. The gold standard is hierarchical (multilevel) models, which respect grouping structures (see 4.3 Mixed-effects regression).
If the expected frequencies are low, it is recommended to use Fisher’s Exact Test instead. In corpus linguistics, the log-likelihood ratio test (\(G\)-test) is also commonly used. Note, however, that it relies on the same large-sample approximation as the \(\chi^2\)-test and is therefore not a remedy for small expected frequencies.
While the \(\chi^2\)-test can only approximate the \(p\)-value, Fisher’s Exact Test can provide an exact solution. Note that for anything more complex than a \(2 \times 2\) table, it becomes considerably more computationally expensive; if it takes too long, set simulate.p.value = TRUE.
Drawing on the hypergeometric distribution (see ?dhyper()), it sums up the probabilities of all frequency tables with the same row and column totals that are as extreme as or more extreme than the one observed.
fisher.test(observed_freqs)
Fisher's Exact Test for Count Data
data: observed_freqs
p-value < 2.2e-16
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval:
0.07722662 0.10118258
sample estimates:
odds ratio
0.08841846
The \(G^2\)-statistic is analogous to \(\chi^2\) and usually yields very similar results for large samples. It is defined as
\[ G^2 = 2\sum_{i=1}^{I}\sum_{j=1}^{J} f_{ij} \ln\left({\frac{f_{ij}}{e_{ij}}}\right) \tag{5}\]
and implemented in R via the DescTools package.
# Load library (install if necessary)
library(DescTools)
# Perform G-test (preferably for tables with more than 2 rows/columns)
GTest(observed_freqs)
Log likelihood ratio (G-test) test of independence without correction
data: observed_freqs
G = 1502.8, X-squared df = 1, p-value < 2.2e-16
How do I make sense of the test results?
The test output has three ‘ingredients’:
- the chi-squared score (X-squared)
- the degrees of freedom (df)
- the p-value.
It is essential to report all three of them, since the \(p\)-value is determined by the other two. Here are a few possible wordings that could be used:
According to a \(\chi^2\)-test, there is a highly significant association between genitive type and possessor animacy at \(p < 0.001\) (\(\chi^2\) = 1453.36, \(df = 1\)), thus justifying the rejection of \(H_0\).
A \(\chi^2\)-test revealed a highly significant association between genitive type and possessor animacy (\(\chi^2(1)\) = 1453.36, \(p < 0.001\)), supporting the rejection of \(H_0\).
The \(\chi^2\)-test results (\(\chi^2\) = 1453.36, \(df = 1\), \(p < 0.001\)) provide strong evidence against the null hypothesis, demonstrating a significant association between genitive type and possessor animacy.
On the whole, the test results suggest that the dependent variable Type and the explanatory variable Possessor Animacy are not independent of each other. If \(H_0\) were true, the probability of observing a distribution at least this extreme would be lower than 0.05 (in fact, it is \(< 2.2 \cdot 10^{-16}\)), which is sufficient to reject the null hypothesis.
We can infer that genitive Type and possessor animacy are associated: The choice between the two variants appears to depend on the animacy of the possessor (although the test by itself cannot establish a causal relationship). However, there are still several things the test does not tell us:
Are there certain variable combinations that contribute particularly strongly to the \(\chi^2\) score?
How strong is the association between
TypeandPossessor Animacy?
Pearson residuals
If we’re interested in which cells show the greatest differences between observed and expected frequencies, an option would be to inspect the Pearson residuals. They correspond to the square root of each cell’s contribution to the \(\chi^2\) score, with a sign indicating whether the observed frequency is higher (+) or lower (−) than expected:
\[ \text{residuals} = \frac{\text{observed} - \text{expected}}{\sqrt{\text{expected}}} \tag{6}\]
Under \(H_0\), Pearson residuals roughly behave like \(z\)-scores and can be accessed via the test results stored in freqs_test. Strictly speaking, it is the standardised residuals (freqs_test$stdres) that follow a standard normal distribution \(N(0, 1)\) under \(H_0\); the Pearson residuals tend to be somewhat smaller.
freqs_test$residuals
animate inanimate
of -18.47557 15.10868
s 23.04185 -18.84282
The function assocplot() can automatically compute the Pearson residuals for any given contingency table and create a plot that highlights their contributions. If the bar is above the dashed line, it is black and indicates that a category is observed more frequently than expected (e.g., of genitives in the inanimate group). Conversely, bars are coloured grey if a category is considerably less frequent than expected, such as s-genitives with inanimate possessors.
assocplot(t(observed_freqs), col = c("black", "lightgrey"))Testing the residuals
The chi-squared test only provides a \(p\)-value for the entire contingency table. But what if we wanted to test the residuals for their significance as well? For a single cell, we can easily obtain the corresponding p-value from the normal distribution. For example, of-genitives with animate possessors have a Pearson residual of \(-18.48\), which suggests that the observed frequency is much lower than the expected frequency. Treating it as a \(z\)-score, the probability of seeing this (or an even lower) value under \(H_0\), \(P(Z \leq -18.48)\), is astronomically small.
pnorm(-18.48, mean = 0, sd = 1)[1] 1.495907e-76
We can conclude that of-genitives with animate possessors are significantly less frequent than expected under the null hypothesis (\(z = -18.48\), \(p < 0.001\)).
Configural frequency analysis
Configural Frequency Analysis (Krauth and Lienert 1973; Schrepp 2006) extends this approach in a convenient way: It tests every cell of the table and systematically controls for multiple comparisons (the so-called family-wise error rate). It performs a significance test for all combinations of variable values in a cross-table. Moreover, CFA is not limited to two variables only. Technically, users can test for associations between arbitrary numbers of variables, but should be aware of the increasing complexity of interpretation.
library(cfa) # install library beforehand
# Get the observed counts and convert them to a data frame
config_df <- as.data.frame(observed_freqs)
# Convert to matrix
configs <- as.matrix(config_df[, 1:2]) # first two columns contain the configurations (= combinations of variable values)
counts <- config_df$Freq # Freq column contains the corresponding counts
# Perform CFA on configurations and counts; apply Bonferroni correction for multiple testing
cfa_output <- cfa(configs, counts, bonferroni = TRUE)
# Print output
print(cfa_output)
*** Analysis of configuration frequencies (CFA) ***
label n expected Q chisq p.chisq sig.chisq z
1 s animate 1451 799.4871 0.1515671 530.9268 0 TRUE 25.09332
2 s inanimate 544 1195.5129 0.1669481 355.0519 0 TRUE -21.53650
3 of animate 592 1243.5129 0.1690271 341.3468 0 TRUE -21.24783
4 of inanimate 2511 1859.4871 0.2011766 228.2722 0 TRUE 18.95630
p.z sig.z
1 0 TRUE
2 1 TRUE
3 1 TRUE
4 0 TRUE
Summary statistics:
Total Chi squared = 1455.598
Total degrees of freedom = 1
p = 0
Sum of counts = 5098
Levels:
Var1 Var2
2 2
We can interpret the findings as follows:
Observed \(>\) Expected
s & animate (significant): The s-genitive occurs more frequently than expected if the possessor is animate (\(\chi^2 = 530.93\), \(p < 0.001\)).
of & inanimate (significant): The of-genitive occurs more frequently than expected if the possessor is inanimate (\(\chi^2 = 228.27\), \(p < 0.001\)).
Observed \(<\) Expected
s & inanimate (significant): The s-genitive occurs less frequently than expected if the possessor is inanimate (\(\chi^2 = 355.05\), \(p < 0.001\)).
of & animate (significant): The of-genitive occurs less frequently than expected if the possessor is animate (\(\chi^2 = 341.35\), \(p < 0.001\)).
The full table (\(n = 5098\)) is significant (\(\chi^2 = 1455.60\), \(p < 0.001\)). Note that CFA reports the \(\chi^2\) value without continuity correction, which is why it is slightly higher than the result of chisq.test() above. Since R rounds extremely small \(p\)-values to 0, they should be reported as \(p < 0.001\).
Effect size
The \(p\)-value only indicates the presence of an association, but not its strength – regardless of how low it may be. For this reason, it is highly recommended to report an effect size measure alongside the \(p\)-value. One such measure is Cramér’s \(V\), which takes values in the interval \([0, 1]\):
\[ V = \sqrt{\frac{\chi^2}{n \times (\min(I, J) - 1)}}, \tag{7}\]
where \(n\) is the sample size and \(\min(I, J)\) the smaller of the number of rows and columns.
The package confintr implements this in its cramersv() function:
cramersv(freqs_test)[1] 0.5339337
The closer \(V\) is to 1, the stronger the association between the two categorical variables. Conversely, \(V = 0\) indicates that there is no association at all in the sample (i.e., the observed frequencies exactly match the expected ones). There are various guidelines in the literature that provide thresholds for “small”, “moderate” and “large” effects, yet these are rarely justified on theoretical grounds and could be viewed as arbitrary.
In CFA, \(Q\) is a cell-wise effect size measure ranging from 0 to 1.
Exercises
Exercise 1 Schröter & Kortmann (2016) investigate the relationship between subject realisation (overt vs. null) and the grammatical category Person (1.p. vs. 2.p. vs. 3.p.) in three varieties of English (British English vs. Hong Kong vs. Singapore). They test the association between subject realisation and person in each of the three varieties, reporting the following test results (2016: 235):
- Singapore English (\(\chi^2 = 3.3245, df = 2, p = 0.1897\))
- Hong Kong English (\(\chi^2 = 40.799, df = 2, p < 0.01\))
- British English (\(\chi^2 = 3.6183, df = 2, p = 0.1638\))
- What hypotheses are the authors testing?
- Assuming a significance level \(\alpha = 0.05\), what statistical conclusions can be drawn from the test results?
- What could be the theoretical implications of these results?
Exercise 2 Using the genitive dataset, write an R script that investigates the association between genitive Type and Genre. Your script should:
- State your null and alternative hypotheses as comments at the top of the script.
- Compute and print a contingency table of observed frequencies.
- Conduct a \(\chi^2\)-test and report the results (\(\chi^2\) value, degrees of freedom and \(p\)-value).
- Calculate an appropriate effect size measure.
- Calculate and print the expected frequencies.
- Compute and visualise the Pearson residuals.
- (Optional) Perform a configural frequency analysis.
- Give a brief theoretical assessment of the results.
Make sure your script is well-commented so that each step is clearly documented.