如何用R中卡方检验高效处理多分类变量的相关性检验
Hey there! I totally get it—running 14×14 pairwise chi-squared tests manually is tedious and error-prone. Let’s walk through a couple of efficient ways to automate this process so you can get all your results in one go.
Method 1: Base R (No Extra Packages Needed)
If you prefer sticking to base R, we can use combn to generate all variable pairs and lapply to run the tests across each pair. Here’s how:
# Step 1: Extract your 14 categorical variables from your data frame # Replace the variable names below with your actual 14 variables cat_vars <- DATA_BASE[, c("TYPE_PEAU", "SENSIBILITE", "VAR3", "VAR4", ...)] # Step 2: Generate all unique pairwise combinations of variables var_pairs <- combn(names(cat_vars), 2, simplify = FALSE) # Step 3: Define a function to run chi-squared tests and format results run_chi_sq <- function(pair) { # Create contingency table for the pair tbl <- table(cat_vars[[pair[1]]], cat_vars[[pair[2]]]) # Run the test test_out <- chisq.test(tbl) # Return a tidy data frame with key results data.frame( Variable_1 = pair[1], Variable_2 = pair[2], Chi_Squared = round(test_out$statistic, 3), Degrees_of_Freedom = test_out$parameter, P_Value = round(test_out$p.value, 4), stringsAsFactors = FALSE ) } # Step 4: Apply the function to all pairs and combine results all_chi_results <- do.call(rbind, lapply(var_pairs, run_chi_sq)) # View the final results print(all_chi_results)
Method 2: Use the rstatix Package (Simpler, Tidy Output)
If you prefer a more streamlined workflow with tidy results, the rstatix package has a built-in function for pairwise chi-squared tests. It handles formatting automatically:
# Install the package if you haven't already # install.packages("rstatix") library(rstatix) # Extract your categorical variables (same as Method 1) cat_vars <- DATA_BASE[, c("TYPE_PEAU", "SENSIBILITE", "VAR3", ...)] # Run pairwise chi-squared tests in one line all_chi_results_rstatix <- pairwise_chisq_test(cat_vars, vars = everything()) # View the tidy results (includes adjustments for multiple comparisons if needed) print(all_chi_results_rstatix)
Important Note: Handling Small Expected Frequencies
Chi-squared tests rely on the assumption that most expected frequencies are ≥5. If more than 20% of your contingency table cells have expected values <5, the test results might be unreliable. We can modify our base R function to check for this and fall back to Fisher’s exact test when needed:
run_chi_or_fisher <- function(pair) { tbl <- table(cat_vars[[pair[1]]], cat_vars[[pair[2]]]) expected_vals <- chisq.test(tbl)$expected # Check if >20% of cells have expected values <5 low_expected <- sum(expected_vals < 5) / length(expected_vals) > 0.2 if (low_expected) { warning(paste("Pair", paste(pair, collapse = " & "), "has too many small expected frequencies—using Fisher's exact test instead.")) test_out <- fisher.test(tbl) return(data.frame( Variable_1 = pair[1], Variable_2 = pair[2], Test_Type = "Fisher's Exact", P_Value = round(test_out$p.value, 4), stringsAsFactors = FALSE )) } else { test_out <- chisq.test(tbl) return(data.frame( Variable_1 = pair[1], Variable_2 = pair[2], Test_Type = "Pearson's Chi-Squared", Chi_Squared = round(test_out$statistic, 3), Degrees_of_Freedom = test_out$parameter, P_Value = round(test_out$p.value, 4), stringsAsFactors = FALSE )) } } # Run the adjusted function all_results_with_check <- do.call(rbind, lapply(var_pairs, run_chi_or_fisher))
This way, you’ll get reliable results without having to manually check each pair.
Hope this saves you a ton of time! If you hit snags with specific variable pairs or need help interpreting the output, feel free to ask.
内容的提问来源于stack exchange,提问作者Rprogrammer

