Contingency Table in R

A contingency table is one of the most widely used tools in statistics for analyzing the relationship between categorical variables. Whether you’re working in healthcare, finance, marketing, manufacturing, or social sciences, contingency tables help summarize data and determine whether two variables are statistically associated.

In R, contingency table analysis is straightforward using built-in functions such as table(), chisq.test(), and fisher.test(), as well as packages like compareGroups for automated statistical reporting.

This guide explains contingency tables, Chi-Square tests, Fisher’s Exact tests, assumptions, and practical R examples.

What Is a Contingency Table?

A contingency table (also called a cross-tabulation or cross-tab) displays the frequency distribution of two or more categorical variables.

Each cell represents the number of observations belonging to a specific combination of categories.

For example, a table may show the relationship between:

  • Gender and Smoking Status
  • Treatment and Recovery
  • Education Level and Employment Status
  • Customer Segment and Product Purchased

A simple 2×2 contingency table looks like this:

SmokerNon-SmokerTotal
Male4555100
Female3070100
Total75125200

The row totals and column totals are known as marginal totals.

Why Use a Contingency Table?

Contingency tables are useful for:

  • Studying relationships between categorical variables
  • Testing statistical independence
  • Comparing proportions across groups
  • Summarizing survey responses
  • Medical research
  • Clinical trials
  • Marketing analytics
  • Quality control

Types of Contingency Tables

Contingency tables are not limited to 2×2 tables.

Common types include:

  • 2 × 2
  • 2 × 3
  • 3 × 3
  • r × c tables
  • Multi-dimensional contingency tables

R can analyze all of these using the same statistical functions.

Chi-Square Test of Independence

The Chi-Square Test of Independence determines whether two categorical variables are associated.

Null Hypothesis (H₀)

The two categorical variables are independent.

Alternative Hypothesis (H₁)

The two categorical variables are associated.

The Chi-Square statistic compares:

  • Observed frequencies
  • Expected frequencies (assuming independence)

The expected frequency for each cell is calculated as:Expected=Row Total×Column TotalGrand TotalExpected = \frac{Row\ Total \times Column\ Total}{Grand\ Total}Expected=Grand TotalRow Total×Column Total​

Large differences between observed and expected frequencies produce a larger Chi-Square statistic.

Assumptions of the Chi-Square Test

Before performing the test, ensure that:

  • Observations are independent.
  • Variables are categorical.
  • Expected cell counts should generally be at least 5.
  • Data are collected using random sampling.

Violation of these assumptions may lead to inaccurate conclusions.

Degrees of Freedom

For an r × c contingency table,df=(r1)(c1)df=(r-1)(c-1)df=(r−1)(c−1)

where:

  • r = number of rows
  • c = number of columns

Decision Rule

  • If p-value < 0.05, reject the null hypothesis.
  • If p-value ≥ 0.05, fail to reject the null hypothesis.

Modern statistical software reports p-values directly, making comparison with Chi-Square critical values unnecessary in most analyses.

Fisher’s Exact Test

Fisher’s Exact Test is an alternative to the Chi-Square test.

It is recommended when:

  • Sample size is small.
  • One or more expected cell counts are less than 5.
  • The contingency table is typically 2×2.

Unlike the Chi-Square test, Fisher’s test computes the exact probability of observing the data under the null hypothesis.

Chi-Square vs Fisher’s Exact Test

FeatureChi-Square TestFisher’s Exact Test
Sample SizeMedium to LargeSmall
Expected Cell Counts≥ 5< 5
Table SizeAnyPrimarily 2×2
P-valueApproximateExact

Goodness-of-Fit Test vs Test of Independence

These two tests are often confused.

Goodness-of-Fit Test

Used to determine whether observed frequencies follow a theoretical distribution.

Examples include:

  • Binomial
  • Poisson
  • Normal
  • Uniform

Null Hypothesis

The observed data follow the specified distribution.

Test of Independence

Used to determine whether two categorical variables are associated.

Although both use the Chi-Square distribution, they answer different research questions.

Creating a Contingency Table in R

Suppose we have information on gender and smoking status.

gender <- c("Male","Male","Female","Female","Male","Female",
"Male","Female","Male","Female")

smoking <- c("Yes","No","No","Yes","Yes","No",
"No","No","Yes","Yes")

tbl <- table(gender, smoking)

tbl

Output

        smoking
gender No Yes
Female 3 2
Male 2 3

Chi-Square Test in R

chisq.test(tbl)

Output

Pearson's Chi-squared test

X-squared = ...
df = 1

p-value = ...

Interpretation

  • p-value < 0.05 → Variables are associated.
  • p-value ≥ 0.05 → Variables are independent.

Check Expected Counts

result <- chisq.test(tbl)

result$expected

Always examine the expected counts before interpreting the Chi-Square test.

Fisher’s Exact Test in R

fisher.test(tbl)

This function automatically computes the exact p-value.

Automatically Choose the Appropriate Test

The compareGroups package can automatically select either the Chi-Square or Fisher’s Exact test depending on the expected cell counts.

install.packages("compareGroups")

library(compareGroups)

ans <- compareGroups(
Groups ~ .,
data = data,
max.ylev = 30,
max.x.lev = 20
)

update(
ans,
method = 3,
show.all = TRUE
)

Here,

  • method = 3 tells the package to automatically perform either the Chi-Square test or Fisher’s Exact test based on the data.
  • show.all = TRUE displays all variable levels in the output.

This approach is particularly useful when generating descriptive statistics tables for clinical studies or survey analyses.

Structural Zeros and Incomplete Tables

Sometimes contingency tables contain zero counts.

Two situations may arise:

Sampling Zero

A category happens to have no observations in the sample.

Structural Zero

A combination of categories is impossible by definition.

For example:

PregnancyMale
Yes0

This zero is structural because males cannot be pregnant.

Structural zeros require special consideration during statistical analysis.

Practical Applications

Contingency tables are extensively used in:

  • Healthcare and epidemiology
  • Clinical research
  • Banking risk analysis
  • Insurance analytics
  • Customer segmentation
  • Marketing campaigns
  • Manufacturing quality control
  • Survey research
  • Machine learning model evaluation
  • Fraud detection

Common Mistakes

Avoid these common errors:

  • Using the Chi-Square test when expected counts are too small.
  • Applying the test to continuous variables without categorization.
  • Ignoring the assumption of independent observations.
  • Interpreting statistical significance as practical significance.
  • Confusing the Goodness-of-Fit test with the Test of Independence.

Conclusion

Contingency tables are an essential part of categorical data analysis in R. They provide a simple yet powerful way to summarize relationships between variables and form the basis for statistical tests such as the Chi-Square Test of Independence and Fisher’s Exact Test.

For larger datasets with adequate expected frequencies, the Chi-Square test is generally appropriate. When sample sizes are small or expected cell counts fall below five, Fisher’s Exact Test provides a more reliable alternative. The compareGroups package further simplifies this process by automatically selecting the appropriate test, making it particularly useful for medical, clinical, and survey-based research.

Understanding when and how to apply these tests ensures more accurate statistical inference and helps avoid incorrect conclusions in categorical data analysis.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

4 × one =