r - 将 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
解决方案
您可以使用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 日创建
推荐阅读
- ios - 强制 UITextView 按需呈现文本?
- javascript - 从组件中隐藏 Angular 6 中的引导对话框
- sql - 使用 SQL 中的日期表将工作日添加到另一个表
- c++ - 如何在gecode中打印变量的值
- flutter - flare_flutter 动画显示问题
- python - Python:合并两个字典列表,其中一个字典具有唯一列
- game-engine - 如何将 FString 转换为 Char* ?UE4
- python - Numpy all 或 any 没有给我想要的结果
- flutter - 在颤振中如何从函数中获取值?
- reactjs - 在已经更新后再次更新状态