R chisq.test() function - Chi-square test
The R chisq.test() function is used to perform the chi-square test, testing the independence or goodness of fit between categorical variables.
The chi-square test is often used to analyze whether there is an association between two categorical variables in a contingency table.
The syntax format of the chisq.test() function is as follows:
chisq.test(x, y = NULL, correct = TRUE)
Parameter description:
xContingency table (matrix) or numeric vector.
yOptional, second vector.
correctWhether to use Yates' continuity correction (only for 2x2 tables), default is TRUE.
Example
# Create contingency table: gender and whether purchased
# 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")
print("Contingency table:")
print(data_table)
# Chi-square test
result <- chisq.test(data_table)
print(result)
# 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")
print("Contingency table:")
print(data_table)
# Chi-square test
result <- chisq.test(data_table)
print(result)
Executing the above code produces the following output:
[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
p value > 0.05, indicating that at the 0.05 significance level, there is no significant association between gender and purchasing behavior.
Other extensions
R language examples