2024-10-31

The Chi-Squared Test

  • A statistical test to determine if there is a significant difference between observed and expected data with contingency table

The Formula

The Chi-squared statistic is expressed as:
\[ \chi^2 = \sum \frac{(O_i - E_i)^2}{E_i} \]

Terms:

  • \(O_i\) = Observed frequency
  • \(E_i\) = Expected frequency

Example

  • Suppose we are determining the association between age and preference for a product.
data_df <- data.frame(
  Like = c(50, 20),
  Neutral = c(30, 50),
  Dislike = c(20, 80)
)

rownames(data_df) <- c("18", "44")
data_matrix <- as.matrix(data_df)

Example Continued

  • Look at this table:

\[ \begin{array}{|c|c|c|c|} \hline \text{Age Group} & \text{Like} & \text{Neutral} & \text{Dislike} \\ \hline 18 & 50 & 30 & 20 \\ 44 & 20 & 50 & 80 \\ \hline \end{array} \]

We can use the following function to compute the Chi-Squared Statistic:

  • chisq.test()

R Code and Results

data <- data.frame(
  Age = c(rep("25 Years Old", 3), rep("44 Years Old", 3)),
  Preference = rep(c("Like", "Neutral", "Dislike"), 2),
  Number = c(50, 30, 20, 20, 50, 80)
)
   
data_wide <- data %>%
  pivot_wider(names_from = Preference, values_from = Number)
chisq_result <- chisq.test(data_wide[, -1])
print(chisq_result)
## 
##  Pearson's Chi-squared test
## 
## data:  data_wide[, -1]
## X-squared = 45.685, df = 2, p-value = 1.202e-10

Plot 1

Plot 2

Plot 3

Conclusion

  • The Chi-squared test is an important test for statistics with contingency tables.
  • It can be used in many important fields of study such as medicine, economics, and biology.