我有一个带有计数号的数据帧,我希望对变量集群的每个值执行一个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)))
发布于 2020-06-25 10:18:59
首先,利用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 chi平方测试。
mantelhaen.test(tab)
# Cochran-Mantel-Haenszel test
#
# data: tab
# Cochran-Mantel-Haenszel M^2 = 59.587, df = 3, p-value = 7.204e-13
https://stackoverflow.com/questions/62572502
复制相似问题