首页 > 解决方案 > 将 t 检验结果分组到 tidyverse 中的列中

问题描述

我想将多个 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

标签: rdplyrpurrrbroom

解决方案


您可以使用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 包(v0.3.0)于 2020 年 9 月 2 日创建


推荐阅读