Joe*_*p_S 1 r chi-squared contingency
chisq.test
我有一个包含计数的数据框,我想对变量 Cluster 的每个值执行 a 。所以基本上,我需要 4 个列联表(对于“A”、“B”、“C”、“D”),其中行 = 类别,列 = 药物,值 = 总计。随后chisq.test
应该对所有 4 个表格运行 a。
示例数据框
df <- data.frame(Cluster = c(rep("A",8),rep("B",8),rep("C",8),rep("D",8)),
Category = rep(c(rep("0-1",2),rep("2-4",2),rep("5-12",2),rep(">12",2)),2),
Drug = rep(c("drug X","drug Y"),16),
Total = as.numeric(sample(20:200,32,replace=TRUE)))
Run Code Online (Sandbox Code Playgroud)
首先,用于xtabs()
生成分层列联表。
tab <- xtabs(Total ~ Category + Drug + Cluster, df)
tab
# , , Cluster = A
#
# Drug
# Category drug X drug Y
# >12 92 75
# 0-1 33 146
# 2-4 193 95
# 5-12 76 195
#
# etc.
Run Code Online (Sandbox Code Playgroud)
然后用于apply()
对每个层进行 Pearson 卡方检验。
apply(tab, 3, chisq.test)
# $A
#
# Pearson's Chi-squared test
#
# data: array(newX[, i], d.call, dn.call)
# X-squared = 145.98, df = 3, p-value < 2.2e-16
#
# etc.
Run Code Online (Sandbox Code Playgroud)
此外,您可以执行条件独立性的Cochran-Mantel-Haenszel 卡方检验。
mantelhaen.test(tab)
# Cochran-Mantel-Haenszel test
#
# data: tab
# Cochran-Mantel-Haenszel M^2 = 59.587, df = 3, p-value = 7.204e-13
Run Code Online (Sandbox Code Playgroud)