R根据列值对数据帧执行多重卡方检验
R perform multiple chi square test on dataframe based on column value
我有一个带有计数的数据框,我想对变量 Cluster 的每个值执行 chisq.test
。所以基本上,我需要 4 个列联表(“A”、“B”、“C”、“D”),其中行 = 类别,列 = 药物,值 = 总计。随后,对于所有 4 个表格,chisq.test
应该是 运行。
示例数据框
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)))
首先,使用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.
然后使用apply()
对每一层进行皮尔逊卡方检验。
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.
此外,您可以对 条件独立性.
执行 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
我有一个带有计数的数据框,我想对变量 Cluster 的每个值执行 chisq.test
。所以基本上,我需要 4 个列联表(“A”、“B”、“C”、“D”),其中行 = 类别,列 = 药物,值 = 总计。随后,对于所有 4 个表格,chisq.test
应该是 运行。
示例数据框
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)))
首先,使用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.
然后使用apply()
对每一层进行皮尔逊卡方检验。
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.
此外,您可以对 条件独立性.
执行 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