【问题标题】:R perform multiple chi square test on dataframe based on column valueR根据列值对数据框执行多个卡方检验
【发布时间】:2020-10-15 17:49:28
【问题描述】:

我有一个包含计数的数据框,我想为变量 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)))

【问题讨论】:

    标签: r chi-squared contingency


    【解决方案1】:

    首先,使用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() 对每个层进行 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.
    

    此外,您可以对条件独立性执行 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
    

    【讨论】:

    • 非常感谢!我预计会有更复杂的事情,但我自己永远不会找到这个解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 2015-06-11
    • 1970-01-01
    • 2020-12-29
    相关资源
    最近更新 更多