【问题标题】:Conduct Multiple T-Tests in R, Condensed在 R 中进行多个 T 检验,精简
【发布时间】:2019-07-22 00:25:18
【问题描述】:

我希望在 R 中进行多个 t 检验,而不必复制粘贴每个测试。在查看“Level_#”时,每个测试将在“类型”(无论是“左”还是“右”)中是否存在差异。目前,我可能有:

t.test(Level_1 ~ Type, alternative="two.sided", conf.level=0.99)
t.test(Level_2 ~ Type, alternative="two.sided", conf.level=0.99)

Type Level_1 Level_2 Level_3
Left      17      50      98
Right     18      65      65
Left      23       7      19
Left      65       7     100
Right     9       13      17

问题是我有数百个“Level_#”,想知道如何自动化这个过程并输出结果的数据框。我的想法是以某种方式合并一个 apply 函数。

【问题讨论】:

    标签: r dataframe hypothesis-test


    【解决方案1】:

    您可以使用tidyverse 方法和purrr 和broom 包来实现。

    require(tidyverse)
    require(broom)
    
    df %>% 
      gather(var, level, -type) %>% 
      nest(-var) %>%
      mutate(model = purrr::map(data, function(x) { 
        t.test(level ~ type, alternative="two.sided", conf.level=0.99, 
               data = x)}), 
        value = purrr::map(model, tidy), 
        conf.low = purrr::map(value, "conf.low"),
        conf.high = purrr::map(value, "conf.high"),
        pvalue = purrr::map(value, "p.value")) %>% 
      select(-data, -model, -value)
    

    输出:

         var  conf.low conf.high    pvalue
    1 level1 -3.025393  4.070641 0.6941518
    2 level2 -3.597754  3.356125 0.9260015
    3 level3 -3.955293  3.673493 0.9210724
    

    样本数据:

    set.seed(123)
    df <- data.frame(type = rep(c("left", "right"), 25), 
                     level1 = rnorm(50, mean = 85, sd = 5), 
                     level2 = rnorm(50, mean = 75, sd = 5), 
                     level3 = rnorm(50, mean = 65, sd = 5))
    

    【讨论】:

    猜你喜欢
    • 2015-09-17
    • 2017-05-17
    • 2023-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 2015-09-17
    相关资源
    最近更新 更多