0
0
R Programmingprogramming~5 mins

Chi-squared test in R Programming

Choose your learning style9 modes available
Introduction

The Chi-squared test helps us check if two groups are related or independent by comparing counts in categories.

You want to see if a new medicine affects recovery rates differently between men and women.
You want to check if people prefer different ice cream flavors based on their age group.
You want to find out if a survey response depends on the city where people live.
Syntax
R Programming
chisq.test(x, y = NULL, correct = TRUE, ...)

x can be a table or matrix of counts.

If y is given, it should be a factor or vector to compare with x.

Examples
Test independence on a 2x2 table of counts.
R Programming
counts <- matrix(c(10, 20, 30, 40), nrow = 2)
chisq.test(counts)
Test if counts in one group differ from expected.
R Programming
group <- factor(c('A', 'A', 'B', 'B'))
result <- chisq.test(table(group))
Sample Program

This program tests if liking or disliking something depends on gender using a 2x2 table.

R Programming
counts <- matrix(c(12, 5, 7, 10), nrow = 2, byrow = TRUE)
rownames(counts) <- c('Male', 'Female')
colnames(counts) <- c('Like', 'Dislike')
result <- chisq.test(counts)
print(result)
OutputSuccess
Important Notes

The test works best with counts, not percentages.

Expected counts should be at least 5 for reliable results.

Yates' correction is applied by default for 2x2 tables to avoid overestimating significance.

Summary

The Chi-squared test checks if two categorical variables are related.

Use it with tables of counts, like survey results or group preferences.

Look at the p-value to decide if the relationship is significant or not.