【问题标题】:Group t test result into columns within tidyverse将 t 检验结果分组到 tidyverse 中的列中
【发布时间】:2020-12-21 07:47:51
【问题描述】:

我想将多个 t 检验结果分组到一张表中。原来我的代码是这样的:

tt_data <- iris %>% 
            group_by(Species) %>%
            summarise(p = t.test(Sepal.Length,Petal.Length,alternative="two.sided",paired=T)$p.value,
                estimate = t.test(Sepal.Length,Petal.Length,alternative="two.sided",paired=T)$estimate
            )

tt_data
# Species    p              estimate
# setosa     2.542887e-51   3.544
# versicolor 9.667914e-36   1.676
# virginica  7.985259e-28   1.036

但是,基于我应该只执行一次统计测试的想法,有没有办法让我每组运行一次​​ t 测试并收集预期的表?我认为 broom 和 purrr 有一些组合,但我不熟悉语法。

# code idea (I know this won't work!)
tt_data <- iris %>% 
            group_by(Species) %>%
            summarise(tt = t.test(Sepal.Length,Petal.Length,alternative="two.sided",paired=T)) %>%
            select(Species, tt.p, tt.estimate)

tt_data
# Species    tt.p           tt.estimate
# setosa     2.542887e-51   3.544
# versicolor 9.667914e-36   1.676
# virginica  7.985259e-28   1.036

【问题讨论】:

    标签: r dplyr purrr broom


    【解决方案1】:

    您可以使用broom::tidy() 将 t.test 的结果转换为整洁的“tibble”:

    library(dplyr)
    library(broom)
    
    iris %>% 
      group_by(Species) %>%
      group_modify(~{
        t.test(.$Sepal.Length,.$Petal.Length,alternative="two.sided",paired=T) %>% 
          tidy()
      }) %>% 
      select(estimate, p.value)
    
    #> Adding missing grouping variables: `Species`
    #> # A tibble: 3 x 3
    #> # Groups:   Species [3]
    #>   Species    estimate  p.value
    #>   <fct>         <dbl>    <dbl>
    #> 1 setosa         3.54 2.54e-51
    #> 2 versicolor     1.68 9.67e-36
    #> 3 virginica      1.04 7.99e-28
    

    reprex package (v0.3.0) 于 2020 年 9 月 2 日创建

    【讨论】:

      【解决方案2】:

      您可以使用mapt.test 生成的列表中选择所需的值,并通过broom::tidy 将其整理成一个数据框,即

      library(dplyr)
      
      iris %>%
        group_by(Species) %>%
        summarise(p = list(broom::tidy(t.test(Sepal.Length, Petal.Length, alternative = "two.sided", paired = T)))) %>% 
        mutate(p.value = purrr::map(p, ~select(.x, c('p.value', 'estimate')))) %>% 
        select(-p) %>% 
        unnest()
      
      
      # A tibble: 3 x 3
      #  Species     p.value estimate
      #  <fct>         <dbl>    <dbl>
      #1 setosa     2.54e-51     3.54
      #2 versicolor 9.67e-36     1.68
      #3 virginica  7.99e-28     1.04
      

      【讨论】:

        猜你喜欢
        • 2020-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-07
        相关资源
        最近更新 更多