R chisq.test() Function - Chi-Square Test
The R chisq.test() function is used to perform a chi-square test, checking the independence or goodness of fit between categorical variables.
The chi-square test is often used to analyze whether two categorical variables in a contingency table are associated.
The syntax of the chisq.test() function is as follows:
chisq.test(x, y = NULL, correct = TRUE)
Parameter Description:
-
x A contingency table (matrix) or numeric vector.
-
y Optional, a second vector.
-
correct Whether to use Yates' continuity correction (only for 2x2 tables), defaulting to TRUE.
Example
Create a contingency table: gender and whether a purchase was made
Purchased Not Purchased
Male 40 20
Female 30 30
data_table
<-
matrix
(
c
(
40
,
20
,
30
,
30
)
,
nrow
=
2
,
byrow
=
TRUE
)
colnames
(
data_table
)
<-
c
(
"Purchased"
,
"Not Purchased"
)
rownames
(
data_table
)
<-
c
(
"Male"
,
"Female"
)
(
"Contingency Table:"
)
(
data_table
)
Chi-square test
result
<-
chisq.test
(
data_table
)
(
result
)
The output of the code above is:
[1] "列联表:"
购买 未购买
男性 40 20
女性 30 30
Pearson's Chi-squared test with Yates' continuity correction
data: data_table
X-squared = 3.2812, df = 1, p-value = 0.07008
The p-value > 0.05 indicates that at the 0.05 significance level, there is no significant association between gender and purchasing behavior.
R Language Examples