将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,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检验并收集预期的表?我认为扫帚和purrr的组合有些,但是我对语法不熟悉。

# code idea (I kNow this won't work!)
tt_data <- iris %>% 
            group_by(Species) %>%
            summarise(tt = t.test(Sepal.Length,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

解决方法

您可以使用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-09-02创建

,

您可以使用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